Fix for a bug in PKCS#7 code and non-detached data.
[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 <assert.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #ifdef NO_STDIO
64 #define APPS_WIN16
65 #endif
66 #include "apps.h"
67 #include <openssl/bio.h>
68 #include <openssl/asn1.h>
69 #include <openssl/err.h>
70 #include <openssl/bn.h>
71 #include <openssl/evp.h>
72 #include <openssl/x509.h>
73 #include <openssl/x509v3.h>
74 #include <openssl/objects.h>
75 #include <openssl/pem.h>
76
77 #undef PROG
78 #define PROG x509_main
79
80 #undef POSTFIX
81 #define POSTFIX ".srl"
82 #define DEF_DAYS        30
83
84 #define CERT_HDR        "certificate"
85
86 static char *x509_usage[]={
87 "usage: x509 args\n",
88 " -inform arg     - input format - default PEM (one of DER, NET or PEM)\n",
89 " -outform arg    - output format - default PEM (one of DER, NET or PEM)\n",
90 " -keyform arg    - private key format - default PEM\n",
91 " -CAform arg     - CA format - default PEM\n",
92 " -CAkeyform arg  - CA key format - default PEM\n",
93 " -in arg         - input file - default stdin\n",
94 " -out arg        - output file - default stdout\n",
95 " -serial         - print serial number value\n",
96 " -hash           - print hash value\n",
97 " -subject        - print subject DN\n",
98 " -issuer         - print issuer DN\n",
99 " -startdate      - notBefore field\n",
100 " -enddate        - notAfter field\n",
101 " -purpose        - print out certificate purposes\n",
102 " -dates          - both Before and After dates\n",
103 " -modulus        - print the RSA key modulus\n",
104 " -fingerprint    - print the certificate fingerprint\n",
105 " -alias          - output certificate alias\n",
106 " -noout          - no certificate output\n",
107 " -trustout       - output a \"trusted\" certificate\n",
108 " -clrtrust       - clear all trusted purposes\n",
109 " -clrnotrust     - clear all untrusted purposes\n",
110 " -addtrust arg   - mark certificate as trusted for a given purpose\n",
111 " -addnotrust arg - mark certificate as not trusted for a given purpose\n",
112 " -setalias arg   - set certificate alias\n",
113 " -days arg       - How long till expiry of a signed certificate - def 30 days\n",
114 " -signkey arg    - self sign cert with arg\n",
115 " -x509toreq      - output a certification request object\n",
116 " -req            - input is a certificate request, sign and output.\n",
117 " -CA arg         - set the CA certificate, must be PEM format.\n",
118 " -CAkey arg      - set the CA key, must be PEM format\n",
119 "                   missing, it is asssumed to be in the CA file.\n",
120 " -CAcreateserial - create serial number file if it does not exist\n",
121 " -CAserial       - serial file\n",
122 " -text           - print the certificate in text form\n",
123 " -C              - print out C code forms\n",
124 " -md2/-md5/-sha1/-mdc2 - digest to do an RSA sign with\n",
125 " -extfile        - configuration file with X509V3 extensions to add\n",
126 " -extensions     - section from config file with X509V3 extensions to add\n",
127 NULL
128 };
129
130 static int MS_CALLBACK callb(int ok, X509_STORE_CTX *ctx);
131 static EVP_PKEY *load_key(char *file, int format);
132 static X509 *load_cert(char *file, int format);
133 static int sign (X509 *x, EVP_PKEY *pkey,int days,const EVP_MD *digest,
134                                                 LHASH *conf, char *section);
135 static int x509_certify (X509_STORE *ctx,char *CAfile,const EVP_MD *digest,
136                          X509 *x,X509 *xca,EVP_PKEY *pkey,char *serial,
137                          int create,int days, LHASH *conf, char *section);
138 static int efunc(X509_PURPOSE *pt, void *arg);
139 static int reqfile=0;
140
141 typedef struct {
142 BIO *bio;
143 X509 *cert;
144 } X509_PPRINT;
145
146 int MAIN(int argc, char **argv)
147         {
148         int ret=1;
149         X509_REQ *req=NULL;
150         X509 *x=NULL,*xca=NULL;
151         EVP_PKEY *Upkey=NULL,*CApkey=NULL;
152         int i,num,badops=0;
153         BIO *out=NULL;
154         BIO *STDout=NULL;
155         STACK *trust = NULL, *notrust = NULL;
156         int informat,outformat,keyformat,CAformat,CAkeyformat;
157         char *infile=NULL,*outfile=NULL,*keyfile=NULL,*CAfile=NULL;
158         char *CAkeyfile=NULL,*CAserial=NULL;
159         char *alias=NULL, *trstr=NULL;
160         int text=0,serial=0,hash=0,subject=0,issuer=0,startdate=0,enddate=0;
161         int noout=0,sign_flag=0,CA_flag=0,CA_createserial=0;
162         int trustout=0,clrtrust=0,clrnotrust=0,aliasout=0;
163         int C=0;
164         int x509req=0,days=DEF_DAYS,modulus=0;
165         int pprint = 0;
166         char **pp;
167         X509_STORE *ctx=NULL;
168         X509_REQ *rq=NULL;
169         int fingerprint=0;
170         char buf[256];
171         const EVP_MD *md_alg,*digest=EVP_md5();
172         LHASH *extconf = NULL;
173         char *extsect = NULL, *extfile = NULL;
174         int need_rand = 0;
175
176         reqfile=0;
177
178         apps_startup();
179
180         if (bio_err == NULL)
181                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
182         STDout=BIO_new_fp(stdout,BIO_NOCLOSE);
183
184         informat=FORMAT_PEM;
185         outformat=FORMAT_PEM;
186         keyformat=FORMAT_PEM;
187         CAformat=FORMAT_PEM;
188         CAkeyformat=FORMAT_PEM;
189
190         ctx=X509_STORE_new();
191         if (ctx == NULL) goto end;
192         X509_STORE_set_verify_cb_func(ctx,callb);
193
194         argc--;
195         argv++;
196         num=0;
197         while (argc >= 1)
198                 {
199                 if      (strcmp(*argv,"-inform") == 0)
200                         {
201                         if (--argc < 1) goto bad;
202                         informat=str2fmt(*(++argv));
203                         }
204                 else if (strcmp(*argv,"-outform") == 0)
205                         {
206                         if (--argc < 1) goto bad;
207                         outformat=str2fmt(*(++argv));
208                         }
209                 else if (strcmp(*argv,"-keyform") == 0)
210                         {
211                         if (--argc < 1) goto bad;
212                         keyformat=str2fmt(*(++argv));
213                         }
214                 else if (strcmp(*argv,"-req") == 0)
215                         {
216                         reqfile=1;
217                         need_rand = 1;
218                         }
219                 else if (strcmp(*argv,"-CAform") == 0)
220                         {
221                         if (--argc < 1) goto bad;
222                         CAformat=str2fmt(*(++argv));
223                         }
224                 else if (strcmp(*argv,"-CAkeyform") == 0)
225                         {
226                         if (--argc < 1) goto bad;
227                         CAformat=str2fmt(*(++argv));
228                         }
229                 else if (strcmp(*argv,"-days") == 0)
230                         {
231                         if (--argc < 1) goto bad;
232                         days=atoi(*(++argv));
233                         if (days == 0)
234                                 {
235                                 BIO_printf(STDout,"bad number of days\n");
236                                 goto bad;
237                                 }
238                         }
239                 else if (strcmp(*argv,"-extfile") == 0)
240                         {
241                         if (--argc < 1) goto bad;
242                         extfile= *(++argv);
243                         }
244                 else if (strcmp(*argv,"-extensions") == 0)
245                         {
246                         if (--argc < 1) goto bad;
247                         extsect= *(++argv);
248                         }
249                 else if (strcmp(*argv,"-in") == 0)
250                         {
251                         if (--argc < 1) goto bad;
252                         infile= *(++argv);
253                         }
254                 else if (strcmp(*argv,"-out") == 0)
255                         {
256                         if (--argc < 1) goto bad;
257                         outfile= *(++argv);
258                         }
259                 else if (strcmp(*argv,"-signkey") == 0)
260                         {
261                         if (--argc < 1) goto bad;
262                         keyfile= *(++argv);
263                         sign_flag= ++num;
264                         need_rand = 1;
265                         }
266                 else if (strcmp(*argv,"-CA") == 0)
267                         {
268                         if (--argc < 1) goto bad;
269                         CAfile= *(++argv);
270                         CA_flag= ++num;
271                         need_rand = 1;
272                         }
273                 else if (strcmp(*argv,"-CAkey") == 0)
274                         {
275                         if (--argc < 1) goto bad;
276                         CAkeyfile= *(++argv);
277                         }
278                 else if (strcmp(*argv,"-CAserial") == 0)
279                         {
280                         if (--argc < 1) goto bad;
281                         CAserial= *(++argv);
282                         }
283                 else if (strcmp(*argv,"-addtrust") == 0)
284                         {
285                         if (--argc < 1) goto bad;
286                         trstr= *(++argv);
287                         if(!X509_trust_set_bit_asc(NULL, trstr, 0)) {
288                                 BIO_printf(bio_err,
289                                         "Unknown trust value %s\n", trstr);
290                                 goto bad;
291                         }
292                         if(!trust) trust = sk_new_null();
293                         sk_push(trust, trstr);
294                         trustout = 1;
295                         }
296                 else if (strcmp(*argv,"-addnotrust") == 0)
297                         {
298                         if (--argc < 1) goto bad;
299                         trstr= *(++argv);
300                         if(!X509_notrust_set_bit_asc(NULL, trstr, 0)) {
301                                 BIO_printf(bio_err,
302                                         "Unknown trust value %s\n", trstr);
303                                 goto bad;
304                         }
305                         if(!notrust) notrust = sk_new_null();
306                         sk_push(notrust, trstr);
307                         trustout = 1;
308                         }
309                 else if (strcmp(*argv,"-setalias") == 0)
310                         {
311                         if (--argc < 1) goto bad;
312                         alias= *(++argv);
313                         trustout = 1;
314                         }
315                 else if (strcmp(*argv,"-setalias") == 0)
316                         {
317                         if (--argc < 1) goto bad;
318                         alias= *(++argv);
319                         trustout = 1;
320                         }
321                 else if (strcmp(*argv,"-C") == 0)
322                         C= ++num;
323                 else if (strcmp(*argv,"-serial") == 0)
324                         serial= ++num;
325                 else if (strcmp(*argv,"-modulus") == 0)
326                         modulus= ++num;
327                 else if (strcmp(*argv,"-x509toreq") == 0)
328                         x509req= ++num;
329                 else if (strcmp(*argv,"-text") == 0)
330                         text= ++num;
331                 else if (strcmp(*argv,"-hash") == 0)
332                         hash= ++num;
333                 else if (strcmp(*argv,"-subject") == 0)
334                         subject= ++num;
335                 else if (strcmp(*argv,"-issuer") == 0)
336                         issuer= ++num;
337                 else if (strcmp(*argv,"-fingerprint") == 0)
338                         fingerprint= ++num;
339                 else if (strcmp(*argv,"-dates") == 0)
340                         {
341                         startdate= ++num;
342                         enddate= ++num;
343                         }
344                 else if (strcmp(*argv,"-purpose") == 0)
345                         pprint= ++num;
346                 else if (strcmp(*argv,"-startdate") == 0)
347                         startdate= ++num;
348                 else if (strcmp(*argv,"-enddate") == 0)
349                         enddate= ++num;
350                 else if (strcmp(*argv,"-noout") == 0)
351                         noout= ++num;
352                 else if (strcmp(*argv,"-trustout") == 0)
353                         trustout= 1;
354                 else if (strcmp(*argv,"-clrtrust") == 0)
355                         clrtrust= ++num;
356                 else if (strcmp(*argv,"-clrnotrust") == 0)
357                         clrnotrust= ++num;
358                 else if (strcmp(*argv,"-alias") == 0)
359                         aliasout= ++num;
360                 else if (strcmp(*argv,"-CAcreateserial") == 0)
361                         CA_createserial= ++num;
362                 else if ((md_alg=EVP_get_digestbyname(&((*argv)[1]))) != NULL)
363                         {
364                         /* ok */
365                         digest=md_alg;
366                         }
367                 else
368                         {
369                         BIO_printf(bio_err,"unknown option %s\n",*argv);
370                         badops=1;
371                         break;
372                         }
373                 argc--;
374                 argv++;
375                 }
376
377         if (badops)
378                 {
379 bad:
380                 for (pp=x509_usage; (*pp != NULL); pp++)
381                         BIO_printf(bio_err,*pp);
382                 goto end;
383                 }
384
385         if (need_rand)
386                 app_RAND_load_file(NULL, bio_err, 0);
387
388         ERR_load_crypto_strings();
389         X509V3_add_standard_extensions();
390         X509_PURPOSE_add_standard();
391
392         if (!X509_STORE_set_default_paths(ctx))
393                 {
394                 ERR_print_errors(bio_err);
395                 goto end;
396                 }
397
398         if ((CAkeyfile == NULL) && (CA_flag) && (CAformat == FORMAT_PEM))
399                 { CAkeyfile=CAfile; }
400         else if ((CA_flag) && (CAkeyfile == NULL))
401                 {
402                 BIO_printf(bio_err,"need to specify a CAkey if using the CA command\n");
403                 goto end;
404                 }
405
406         if (extfile) {
407                 long errorline;
408                 X509V3_CTX ctx2;
409                 if (!(extconf=CONF_load(NULL,extfile,&errorline))) {
410                         if (errorline <= 0)
411                                 BIO_printf(bio_err,
412                                         "error loading the config file '%s'\n",
413                                                                 extfile);
414                         else
415                                 BIO_printf(bio_err,
416                                        "error on line %ld of config file '%s'\n"
417                                                         ,errorline,extfile);
418                         goto end;
419                 }
420                 if(!extsect && !(extsect = CONF_get_string(extconf, "default",
421                                          "extensions"))) extsect = "default";
422                 X509V3_set_ctx_test(&ctx2);
423                 X509V3_set_conf_lhash(&ctx2, extconf);
424                 if(!X509V3_EXT_add_conf(extconf, &ctx2, extsect, NULL)) {
425                         BIO_printf(bio_err,
426                                 "Error Loading extension section %s\n",
427                                                                  extsect);
428                         ERR_print_errors(bio_err);
429                         goto end;
430                 }
431         } 
432
433
434         if (reqfile)
435                 {
436                 EVP_PKEY *pkey;
437                 X509_CINF *ci;
438                 BIO *in;
439
440                 if (!sign_flag && !CA_flag)
441                         {
442                         BIO_printf(bio_err,"We need a private key to sign with\n");
443                         goto end;
444                         }
445                 in=BIO_new(BIO_s_file());
446                 if (in == NULL)
447                         {
448                         ERR_print_errors(bio_err);
449                         goto end;
450                         }
451
452                 if (infile == NULL)
453                         BIO_set_fp(in,stdin,BIO_NOCLOSE|BIO_FP_TEXT);
454                 else
455                         {
456                         if (BIO_read_filename(in,infile) <= 0)
457                                 {
458                                 perror(infile);
459                                 goto end;
460                                 }
461                         }
462                 req=PEM_read_bio_X509_REQ(in,NULL,NULL,NULL);
463                 BIO_free(in);
464
465                 if (req == NULL) { perror(infile); goto end; }
466
467                 if (    (req->req_info == NULL) ||
468                         (req->req_info->pubkey == NULL) ||
469                         (req->req_info->pubkey->public_key == NULL) ||
470                         (req->req_info->pubkey->public_key->data == NULL))
471                         {
472                         BIO_printf(bio_err,"The certificate request appears to corrupted\n");
473                         BIO_printf(bio_err,"It does not contain a public key\n");
474                         goto end;
475                         }
476                 if ((pkey=X509_REQ_get_pubkey(req)) == NULL)
477                         {
478                         BIO_printf(bio_err,"error unpacking public key\n");
479                         goto end;
480                         }
481                 i=X509_REQ_verify(req,pkey);
482                 EVP_PKEY_free(pkey);
483                 if (i < 0)
484                         {
485                         BIO_printf(bio_err,"Signature verification error\n");
486                         ERR_print_errors(bio_err);
487                         goto end;
488                         }
489                 if (i == 0)
490                         {
491                         BIO_printf(bio_err,"Signature did not match the certificate request\n");
492                         goto end;
493                         }
494                 else
495                         BIO_printf(bio_err,"Signature ok\n");
496                 
497                 X509_NAME_oneline(req->req_info->subject,buf,256);
498                 BIO_printf(bio_err,"subject=%s\n",buf);
499
500                 if ((x=X509_new()) == NULL) goto end;
501                 ci=x->cert_info;
502
503                 if (!ASN1_INTEGER_set(X509_get_serialNumber(x),0)) goto end;
504                 if (!X509_set_issuer_name(x,req->req_info->subject)) goto end;
505                 if (!X509_set_subject_name(x,req->req_info->subject)) goto end;
506
507                 X509_gmtime_adj(X509_get_notBefore(x),0);
508                 X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days);
509
510 #if 0
511                 X509_PUBKEY_free(ci->key);
512                 ci->key=req->req_info->pubkey;
513                 req->req_info->pubkey=NULL;
514 #else
515                 pkey = X509_REQ_get_pubkey(req);
516                 X509_set_pubkey(x,pkey);
517                 EVP_PKEY_free(pkey);
518 #endif
519                 }
520         else
521                 x=load_cert(infile,informat);
522
523         if (x == NULL) goto end;
524         if (CA_flag)
525                 {
526                 xca=load_cert(CAfile,CAformat);
527                 if (xca == NULL) goto end;
528                 }
529
530         if (!noout || text)
531                 {
532                 OBJ_create("2.99999.3",
533                         "SET.ex3","SET x509v3 extension 3");
534
535                 out=BIO_new(BIO_s_file());
536                 if (out == NULL)
537                         {
538                         ERR_print_errors(bio_err);
539                         goto end;
540                         }
541                 if (outfile == NULL)
542                         BIO_set_fp(out,stdout,BIO_NOCLOSE);
543                 else
544                         {
545                         if (BIO_write_filename(out,outfile) <= 0)
546                                 {
547                                 perror(outfile);
548                                 goto end;
549                                 }
550                         }
551                 }
552
553         if(alias) X509_alias_set(x, (unsigned char *)alias, -1);
554
555         if(clrtrust) X509_trust_set_bit(x, -1, 0);
556         if(clrnotrust) X509_notrust_set_bit(x, -1, 0);
557
558         if(trust) {
559                 for(i = 0; i < sk_num(trust); i++) {
560                         trstr = sk_value(trust, i);
561                         X509_trust_set_bit_asc(x, trstr, 1);
562                 }
563                 sk_free(trust);
564         }
565
566         if(notrust) {
567                 for(i = 0; i < sk_num(notrust); i++) {
568                         trstr = sk_value(notrust, i);
569                         X509_notrust_set_bit_asc(x, trstr, 1);
570                 }
571                 sk_free(notrust);
572         }
573
574         if (num)
575                 {
576                 for (i=1; i<=num; i++)
577                         {
578                         if (issuer == i)
579                                 {
580                                 X509_NAME_oneline(X509_get_issuer_name(x),
581                                         buf,256);
582                                 BIO_printf(STDout,"issuer= %s\n",buf);
583                                 }
584                         else if (subject == i) 
585                                 {
586                                 X509_NAME_oneline(X509_get_subject_name(x),
587                                         buf,256);
588                                 BIO_printf(STDout,"subject=%s\n",buf);
589                                 }
590                         else if (serial == i)
591                                 {
592                                 BIO_printf(STDout,"serial=");
593                                 i2a_ASN1_INTEGER(STDout,x->cert_info->serialNumber);
594                                 BIO_printf(STDout,"\n");
595                                 }
596                         else if (aliasout == i)
597                                 {
598                                 unsigned char *alstr;
599                                 alstr = X509_alias_get(x, NULL);
600                                 if(alstr) BIO_printf(STDout,"%s\n", alstr);
601                                 else BIO_puts(STDout,"<No Alias>\n");
602                                 }
603                         else if (hash == i)
604                                 {
605                                 BIO_printf(STDout,"%08lx\n",X509_subject_name_hash(x));
606                                 }
607                         else if (pprint == i)
608                                 {
609                                 X509_PPRINT ptmp;
610                                 ptmp.bio = STDout;
611                                 ptmp.cert = x;
612                                 BIO_printf(STDout, "Certificate purposes:\n");
613                                 X509_PURPOSE_enum(efunc, &ptmp);
614                                 }
615                         else
616                                 if (modulus == i)
617                                 {
618                                 EVP_PKEY *pkey;
619
620                                 pkey=X509_get_pubkey(x);
621                                 if (pkey == NULL)
622                                         {
623                                         BIO_printf(bio_err,"Modulus=unavailable\n");
624                                         ERR_print_errors(bio_err);
625                                         goto end;
626                                         }
627                                 BIO_printf(STDout,"Modulus=");
628 #ifndef NO_RSA
629                                 if (pkey->type == EVP_PKEY_RSA)
630                                         BN_print(STDout,pkey->pkey.rsa->n);
631                                 else
632 #endif
633 #ifndef NO_DSA
634                                 if (pkey->type == EVP_PKEY_DSA)
635                                         BN_print(STDout,pkey->pkey.dsa->pub_key);
636                                 else
637 #endif
638                                         BIO_printf(STDout,"Wrong Algorithm type");
639                                 BIO_printf(STDout,"\n");
640                                 EVP_PKEY_free(pkey);
641                                 }
642                         else
643                                 if (C == i)
644                                 {
645                                 unsigned char *d;
646                                 char *m;
647                                 int y,z;
648
649                                 X509_NAME_oneline(X509_get_subject_name(x),
650                                         buf,256);
651                                 BIO_printf(STDout,"/* subject:%s */\n",buf);
652                                 m=X509_NAME_oneline(
653                                         X509_get_issuer_name(x),buf,256);
654                                 BIO_printf(STDout,"/* issuer :%s */\n",buf);
655
656                                 z=i2d_X509(x,NULL);
657                                 m=Malloc(z);
658
659                                 d=(unsigned char *)m;
660                                 z=i2d_X509_NAME(X509_get_subject_name(x),&d);
661                                 BIO_printf(STDout,"unsigned char XXX_subject_name[%d]={\n",z);
662                                 d=(unsigned char *)m;
663                                 for (y=0; y<z; y++)
664                                         {
665                                         BIO_printf(STDout,"0x%02X,",d[y]);
666                                         if ((y & 0x0f) == 0x0f) BIO_printf(STDout,"\n");
667                                         }
668                                 if (y%16 != 0) BIO_printf(STDout,"\n");
669                                 BIO_printf(STDout,"};\n");
670
671                                 z=i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x),&d);
672                                 BIO_printf(STDout,"unsigned char XXX_public_key[%d]={\n",z);
673                                 d=(unsigned char *)m;
674                                 for (y=0; y<z; y++)
675                                         {
676                                         BIO_printf(STDout,"0x%02X,",d[y]);
677                                         if ((y & 0x0f) == 0x0f)
678                                                 BIO_printf(STDout,"\n");
679                                         }
680                                 if (y%16 != 0) BIO_printf(STDout,"\n");
681                                 BIO_printf(STDout,"};\n");
682
683                                 z=i2d_X509(x,&d);
684                                 BIO_printf(STDout,"unsigned char XXX_certificate[%d]={\n",z);
685                                 d=(unsigned char *)m;
686                                 for (y=0; y<z; y++)
687                                         {
688                                         BIO_printf(STDout,"0x%02X,",d[y]);
689                                         if ((y & 0x0f) == 0x0f)
690                                                 BIO_printf(STDout,"\n");
691                                         }
692                                 if (y%16 != 0) BIO_printf(STDout,"\n");
693                                 BIO_printf(STDout,"};\n");
694
695                                 Free(m);
696                                 }
697                         else if (text == i)
698                                 {
699                                 X509_print(out,x);
700                                 }
701                         else if (startdate == i)
702                                 {
703                                 BIO_puts(STDout,"notBefore=");
704                                 ASN1_TIME_print(STDout,X509_get_notBefore(x));
705                                 BIO_puts(STDout,"\n");
706                                 }
707                         else if (enddate == i)
708                                 {
709                                 BIO_puts(STDout,"notAfter=");
710                                 ASN1_TIME_print(STDout,X509_get_notAfter(x));
711                                 BIO_puts(STDout,"\n");
712                                 }
713                         else if (fingerprint == i)
714                                 {
715                                 int j;
716                                 unsigned int n;
717                                 unsigned char md[EVP_MAX_MD_SIZE];
718
719                                 if (!X509_digest(x,EVP_md5(),md,&n))
720                                         {
721                                         BIO_printf(bio_err,"out of memory\n");
722                                         goto end;
723                                         }
724                                 BIO_printf(STDout,"MD5 Fingerprint=");
725                                 for (j=0; j<(int)n; j++)
726                                         {
727                                         BIO_printf(STDout,"%02X%c",md[j],
728                                                 (j+1 == (int)n)
729                                                 ?'\n':':');
730                                         }
731                                 }
732
733                         /* should be in the library */
734                         else if ((sign_flag == i) && (x509req == 0))
735                                 {
736                                 BIO_printf(bio_err,"Getting Private key\n");
737                                 if (Upkey == NULL)
738                                         {
739                                         Upkey=load_key(keyfile,keyformat);
740                                         if (Upkey == NULL) goto end;
741                                         }
742 #ifndef NO_DSA
743                                 if (Upkey->type == EVP_PKEY_DSA)
744                                         digest=EVP_dss1();
745 #endif
746
747                                 assert(need_rand);
748                                 if (!sign(x,Upkey,days,digest,
749                                                  extconf, extsect)) goto end;
750                                 }
751                         else if (CA_flag == i)
752                                 {
753                                 BIO_printf(bio_err,"Getting CA Private Key\n");
754                                 if (CAkeyfile != NULL)
755                                         {
756                                         CApkey=load_key(CAkeyfile,CAkeyformat);
757                                         if (CApkey == NULL) goto end;
758                                         }
759 #ifndef NO_DSA
760                                 if (CApkey->type == EVP_PKEY_DSA)
761                                         digest=EVP_dss1();
762 #endif
763                                 
764                                 assert(need_rand);
765                                 if (!x509_certify(ctx,CAfile,digest,x,xca,
766                                         CApkey, CAserial,CA_createserial,days,
767                                         extconf, extsect))
768                                         goto end;
769                                 }
770                         else if (x509req == i)
771                                 {
772                                 EVP_PKEY *pk;
773
774                                 BIO_printf(bio_err,"Getting request Private Key\n");
775                                 if (keyfile == NULL)
776                                         {
777                                         BIO_printf(bio_err,"no request key file specified\n");
778                                         goto end;
779                                         }
780                                 else
781                                         {
782                                         pk=load_key(keyfile,FORMAT_PEM);
783                                         if (pk == NULL) goto end;
784                                         }
785
786                                 BIO_printf(bio_err,"Generating certificate request\n");
787
788                                 rq=X509_to_X509_REQ(x,pk,EVP_md5());
789                                 EVP_PKEY_free(pk);
790                                 if (rq == NULL)
791                                         {
792                                         ERR_print_errors(bio_err);
793                                         goto end;
794                                         }
795                                 if (!noout)
796                                         {
797                                         X509_REQ_print(out,rq);
798                                         PEM_write_bio_X509_REQ(out,rq);
799                                         }
800                                 noout=1;
801                                 }
802                         }
803                 }
804
805         if (noout)
806                 {
807                 ret=0;
808                 goto end;
809                 }
810
811         if      (outformat == FORMAT_ASN1)
812                 i=i2d_X509_bio(out,x);
813         else if (outformat == FORMAT_PEM) {
814                 if(trustout) i=PEM_write_bio_X509_AUX(out,x);
815                 else i=PEM_write_bio_X509(out,x);
816         } else if (outformat == FORMAT_NETSCAPE)
817                 {
818                 ASN1_HEADER ah;
819                 ASN1_OCTET_STRING os;
820
821                 os.data=(unsigned char *)CERT_HDR;
822                 os.length=strlen(CERT_HDR);
823                 ah.header= &os;
824                 ah.data=(char *)x;
825                 ah.meth=X509_asn1_meth();
826
827                 /* no macro for this one yet */
828                 i=ASN1_i2d_bio(i2d_ASN1_HEADER,out,(unsigned char *)&ah);
829                 }
830         else    {
831                 BIO_printf(bio_err,"bad output format specified for outfile\n");
832                 goto end;
833                 }
834         if (!i) {
835                 BIO_printf(bio_err,"unable to write certificate\n");
836                 ERR_print_errors(bio_err);
837                 goto end;
838                 }
839         ret=0;
840 end:
841         if (need_rand)
842                 app_RAND_write_file(NULL, bio_err);
843         OBJ_cleanup();
844         CONF_free(extconf);
845         BIO_free(out);
846         BIO_free(STDout);
847         X509_STORE_free(ctx);
848         X509_REQ_free(req);
849         X509_free(x);
850         X509_free(xca);
851         EVP_PKEY_free(Upkey);
852         EVP_PKEY_free(CApkey);
853         X509_REQ_free(rq);
854         X509V3_EXT_cleanup();
855         X509_PURPOSE_cleanup();
856         EXIT(ret);
857         }
858
859 static int x509_certify(X509_STORE *ctx, char *CAfile, const EVP_MD *digest,
860              X509 *x, X509 *xca, EVP_PKEY *pkey, char *serialfile, int create,
861              int days, LHASH *conf, char *section)
862         {
863         int ret=0;
864         BIO *io=NULL;
865         MS_STATIC char buf2[1024];
866         char *buf=NULL,*p;
867         BIGNUM *serial=NULL;
868         ASN1_INTEGER *bs=NULL,bs2;
869         X509_STORE_CTX xsc;
870         EVP_PKEY *upkey;
871
872         upkey = X509_get_pubkey(xca);
873         EVP_PKEY_copy_parameters(upkey,pkey);
874         EVP_PKEY_free(upkey);
875
876         X509_STORE_CTX_init(&xsc,ctx,x,NULL);
877         buf=(char *)Malloc(EVP_PKEY_size(pkey)*2+
878                 ((serialfile == NULL)
879                         ?(strlen(CAfile)+strlen(POSTFIX)+1)
880                         :(strlen(serialfile)))+1);
881         if (buf == NULL) { BIO_printf(bio_err,"out of mem\n"); goto end; }
882         if (serialfile == NULL)
883                 {
884                 strcpy(buf,CAfile);
885                 for (p=buf; *p; p++)
886                         if (*p == '.')
887                                 {
888                                 *p='\0';
889                                 break;
890                                 }
891                 strcat(buf,POSTFIX);
892                 }
893         else
894                 strcpy(buf,serialfile);
895         serial=BN_new();
896         bs=ASN1_INTEGER_new();
897         if ((serial == NULL) || (bs == NULL))
898                 {
899                 ERR_print_errors(bio_err);
900                 goto end;
901                 }
902
903         io=BIO_new(BIO_s_file());
904         if (io == NULL)
905                 {
906                 ERR_print_errors(bio_err);
907                 goto end;
908                 }
909         
910         if (BIO_read_filename(io,buf) <= 0)
911                 {
912                 if (!create)
913                         {
914                         perror(buf);
915                         goto end;
916                         }
917                 else
918                         {
919                         ASN1_INTEGER_set(bs,0);
920                         BN_zero(serial);
921                         }
922                 }
923         else 
924                 {
925                 if (!a2i_ASN1_INTEGER(io,bs,buf2,1024))
926                         {
927                         BIO_printf(bio_err,"unable to load serial number from %s\n",buf);
928                         ERR_print_errors(bio_err);
929                         goto end;
930                         }
931                 else
932                         {
933                         serial=BN_bin2bn(bs->data,bs->length,serial);
934                         if (serial == NULL)
935                                 {
936                                 BIO_printf(bio_err,"error converting bin 2 bn");
937                                 goto end;
938                                 }
939                         }
940                 }
941
942         if (!BN_add_word(serial,1))
943                 { BIO_printf(bio_err,"add_word failure\n"); goto end; }
944         bs2.data=(unsigned char *)buf2;
945         bs2.length=BN_bn2bin(serial,bs2.data);
946
947         if (BIO_write_filename(io,buf) <= 0)
948                 {
949                 BIO_printf(bio_err,"error attempting to write serial number file\n");
950                 perror(buf);
951                 goto end;
952                 }
953         i2a_ASN1_INTEGER(io,&bs2);
954         BIO_puts(io,"\n");
955         BIO_free(io);
956         io=NULL;
957         
958         if (!X509_STORE_add_cert(ctx,x)) goto end;
959
960         /* NOTE: this certificate can/should be self signed, unless it was
961          * a certificate request in which case it is not. */
962         X509_STORE_CTX_set_cert(&xsc,x);
963         if (!reqfile && !X509_verify_cert(&xsc))
964                 goto end;
965
966         if (!X509_check_private_key(xca,pkey))
967                 {
968                 BIO_printf(bio_err,"CA certificate and CA private key do not match\n");
969                 goto end;
970                 }
971
972         if (!X509_set_issuer_name(x,X509_get_subject_name(xca))) goto end;
973         if (!X509_set_serialNumber(x,bs)) goto end;
974
975         if (X509_gmtime_adj(X509_get_notBefore(x),0L) == NULL)
976                 goto end;
977
978         /* hardwired expired */
979         if (X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days) == NULL)
980                 goto end;
981
982         if(conf) {
983                 X509V3_CTX ctx2;
984                 X509_set_version(x,2); /* version 3 certificate */
985                 X509V3_set_ctx(&ctx2, xca, x, NULL, NULL, 0);
986                 X509V3_set_conf_lhash(&ctx2, conf);
987                 if(!X509V3_EXT_add_conf(conf, &ctx2, section, x)) goto end;
988         }
989
990         if (!X509_sign(x,pkey,digest)) goto end;
991         ret=1;
992 end:
993         X509_STORE_CTX_cleanup(&xsc);
994         if (!ret)
995                 ERR_print_errors(bio_err);
996         if (buf != NULL) Free(buf);
997         if (bs != NULL) ASN1_INTEGER_free(bs);
998         if (io != NULL) BIO_free(io);
999         if (serial != NULL) BN_free(serial);
1000         return(ret);
1001         }
1002
1003 static int MS_CALLBACK callb(int ok, X509_STORE_CTX *ctx)
1004         {
1005         char buf[256];
1006         int err;
1007         X509 *err_cert;
1008
1009         /* it is ok to use a self signed certificate
1010          * This case will catch both the initial ok == 0 and the
1011          * final ok == 1 calls to this function */
1012         err=X509_STORE_CTX_get_error(ctx);
1013         if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
1014                 return(1);
1015
1016         /* BAD we should have gotten an error.  Normally if everything
1017          * worked X509_STORE_CTX_get_error(ctx) will still be set to
1018          * DEPTH_ZERO_SELF_.... */
1019         if (ok)
1020                 {
1021                 BIO_printf(bio_err,"error with certificate to be certified - should be self signed\n");
1022                 return(0);
1023                 }
1024         else
1025                 {
1026                 err_cert=X509_STORE_CTX_get_current_cert(ctx);
1027                 X509_NAME_oneline(X509_get_subject_name(err_cert),buf,256);
1028                 BIO_printf(bio_err,"%s\n",buf);
1029                 BIO_printf(bio_err,"error with certificate - error %d at depth %d\n%s\n",
1030                         err,X509_STORE_CTX_get_error_depth(ctx),
1031                         X509_verify_cert_error_string(err));
1032                 return(1);
1033                 }
1034         }
1035
1036 static EVP_PKEY *load_key(char *file, int format)
1037         {
1038         BIO *key=NULL;
1039         EVP_PKEY *pkey=NULL;
1040
1041         if (file == NULL)
1042                 {
1043                 BIO_printf(bio_err,"no keyfile specified\n");
1044                 goto end;
1045                 }
1046         key=BIO_new(BIO_s_file());
1047         if (key == NULL)
1048                 {
1049                 ERR_print_errors(bio_err);
1050                 goto end;
1051                 }
1052         if (BIO_read_filename(key,file) <= 0)
1053                 {
1054                 perror(file);
1055                 goto end;
1056                 }
1057 #ifndef NO_RSA
1058         if      (format == FORMAT_ASN1)
1059                 {
1060                 RSA *rsa;
1061
1062                 rsa=d2i_RSAPrivateKey_bio(key,NULL);
1063                 if (rsa != NULL)
1064                         {
1065                         if ((pkey=EVP_PKEY_new()) != NULL)
1066                                 EVP_PKEY_assign_RSA(pkey,rsa);
1067                         else
1068                                 RSA_free(rsa);
1069                         }
1070                 }
1071         else
1072 #endif
1073                 if (format == FORMAT_PEM)
1074                 {
1075                 pkey=PEM_read_bio_PrivateKey(key,NULL,NULL,NULL);
1076                 }
1077         else
1078                 {
1079                 BIO_printf(bio_err,"bad input format specified for key\n");
1080                 goto end;
1081                 }
1082 end:
1083         if (key != NULL) BIO_free(key);
1084         if (pkey == NULL)
1085                 BIO_printf(bio_err,"unable to load Private Key\n");
1086         return(pkey);
1087         }
1088
1089 static X509 *load_cert(char *file, int format)
1090         {
1091         ASN1_HEADER *ah=NULL;
1092         BUF_MEM *buf=NULL;
1093         X509 *x=NULL;
1094         BIO *cert;
1095
1096         if ((cert=BIO_new(BIO_s_file())) == NULL)
1097                 {
1098                 ERR_print_errors(bio_err);
1099                 goto end;
1100                 }
1101
1102         if (file == NULL)
1103                 BIO_set_fp(cert,stdin,BIO_NOCLOSE);
1104         else
1105                 {
1106                 if (BIO_read_filename(cert,file) <= 0)
1107                         {
1108                         perror(file);
1109                         goto end;
1110                         }
1111                 }
1112         if      (format == FORMAT_ASN1)
1113                 x=d2i_X509_bio(cert,NULL);
1114         else if (format == FORMAT_NETSCAPE)
1115                 {
1116                 unsigned char *p,*op;
1117                 int size=0,i;
1118
1119                 /* We sort of have to do it this way because it is sort of nice
1120                  * to read the header first and check it, then
1121                  * try to read the certificate */
1122                 buf=BUF_MEM_new();
1123                 for (;;)
1124                         {
1125                         if ((buf == NULL) || (!BUF_MEM_grow(buf,size+1024*10)))
1126                                 goto end;
1127                         i=BIO_read(cert,&(buf->data[size]),1024*10);
1128                         size+=i;
1129                         if (i == 0) break;
1130                         if (i < 0)
1131                                 {
1132                                 perror("reading certificate");
1133                                 goto end;
1134                                 }
1135                         }
1136                 p=(unsigned char *)buf->data;
1137                 op=p;
1138
1139                 /* First load the header */
1140                 if ((ah=d2i_ASN1_HEADER(NULL,&p,(long)size)) == NULL)
1141                         goto end;
1142                 if ((ah->header == NULL) || (ah->header->data == NULL) ||
1143                         (strncmp(CERT_HDR,(char *)ah->header->data,
1144                         ah->header->length) != 0))
1145                         {
1146                         BIO_printf(bio_err,"Error reading header on certificate\n");
1147                         goto end;
1148                         }
1149                 /* header is ok, so now read the object */
1150                 p=op;
1151                 ah->meth=X509_asn1_meth();
1152                 if ((ah=d2i_ASN1_HEADER(&ah,&p,(long)size)) == NULL)
1153                         goto end;
1154                 x=(X509 *)ah->data;
1155                 ah->data=NULL;
1156                 }
1157         else if (format == FORMAT_PEM)
1158                 x=PEM_read_bio_X509_AUX(cert,NULL,NULL,NULL);
1159         else    {
1160                 BIO_printf(bio_err,"bad input format specified for input cert\n");
1161                 goto end;
1162                 }
1163 end:
1164         if (x == NULL)
1165                 {
1166                 BIO_printf(bio_err,"unable to load certificate\n");
1167                 ERR_print_errors(bio_err);
1168                 }
1169         if (ah != NULL) ASN1_HEADER_free(ah);
1170         if (cert != NULL) BIO_free(cert);
1171         if (buf != NULL) BUF_MEM_free(buf);
1172         return(x);
1173         }
1174
1175 /* self sign */
1176 static int sign(X509 *x, EVP_PKEY *pkey, int days, const EVP_MD *digest, 
1177                                                 LHASH *conf, char *section)
1178         {
1179
1180         EVP_PKEY *pktmp;
1181
1182         pktmp = X509_get_pubkey(x);
1183         EVP_PKEY_copy_parameters(pktmp,pkey);
1184         EVP_PKEY_save_parameters(pktmp,1);
1185         EVP_PKEY_free(pktmp);
1186
1187         if (!X509_set_issuer_name(x,X509_get_subject_name(x))) goto err;
1188         if (X509_gmtime_adj(X509_get_notBefore(x),0) == NULL) goto err;
1189
1190         /* Lets just make it 12:00am GMT, Jan 1 1970 */
1191         /* memcpy(x->cert_info->validity->notBefore,"700101120000Z",13); */
1192         /* 28 days to be certified */
1193
1194         if (X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days) == NULL)
1195                 goto err;
1196
1197         if (!X509_set_pubkey(x,pkey)) goto err;
1198         if(conf) {
1199                 X509V3_CTX ctx;
1200                 X509_set_version(x,2); /* version 3 certificate */
1201                 X509V3_set_ctx(&ctx, x, x, NULL, NULL, 0);
1202                 X509V3_set_conf_lhash(&ctx, conf);
1203                 if(!X509V3_EXT_add_conf(conf, &ctx, section, x)) goto err;
1204         }
1205         if (!X509_sign(x,pkey,digest)) goto err;
1206         return(1);
1207 err:
1208         ERR_print_errors(bio_err);
1209         return(0);
1210         }
1211
1212 static int efunc(X509_PURPOSE *pt, void *arg)
1213 {
1214         X509_PPRINT *ptmp;
1215         int id, i, idret;
1216         char *pname;
1217         ptmp = arg;
1218         id = X509_PURPOSE_get_id(pt);
1219         pname = X509_PURPOSE_get_name(pt);
1220         for(i = 0; i < 2; i++) {
1221                 idret = X509_check_purpose(ptmp->cert, id, i);
1222                 BIO_printf(ptmp->bio, "%s%s : ", pname, i ? " CA" : ""); 
1223                 if(idret == 1) BIO_printf(ptmp->bio, "Yes\n");
1224                 else if (idret == 0) BIO_printf(ptmp->bio, "No\n");
1225                 else BIO_printf(ptmp->bio, "Yes (WARNING code=%d)\n", idret);
1226         }
1227         return 1;
1228 }
1229
1230
1231