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