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