Reduce chances of issuer and serial number duplication by use of random
[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,x->cert_info->serialNumber);
699                                 BIO_printf(STDout,"\n");
700                                 }
701                         else if (email == i) 
702                                 {
703                                 int j;
704                                 STACK *emlst;
705                                 emlst = X509_get1_email(x);
706                                 for (j = 0; j < sk_num(emlst); j++)
707                                         BIO_printf(STDout, "%s\n", sk_value(emlst, j));
708                                 X509_email_free(emlst);
709                                 }
710                         else if (aliasout == i)
711                                 {
712                                 unsigned char *alstr;
713                                 alstr = X509_alias_get0(x, NULL);
714                                 if (alstr) BIO_printf(STDout,"%s\n", alstr);
715                                 else BIO_puts(STDout,"<No Alias>\n");
716                                 }
717                         else if (subject_hash == i)
718                                 {
719                                 BIO_printf(STDout,"%08lx\n",X509_subject_name_hash(x));
720                                 }
721                         else if (issuer_hash == i)
722                                 {
723                                 BIO_printf(STDout,"%08lx\n",X509_issuer_name_hash(x));
724                                 }
725                         else if (pprint == i)
726                                 {
727                                 X509_PURPOSE *ptmp;
728                                 int j;
729                                 BIO_printf(STDout, "Certificate purposes:\n");
730                                 for (j = 0; j < X509_PURPOSE_get_count(); j++)
731                                         {
732                                         ptmp = X509_PURPOSE_get0(j);
733                                         purpose_print(STDout, x, ptmp);
734                                         }
735                                 }
736                         else
737                                 if (modulus == i)
738                                 {
739                                 EVP_PKEY *pkey;
740
741                                 pkey=X509_get_pubkey(x);
742                                 if (pkey == NULL)
743                                         {
744                                         BIO_printf(bio_err,"Modulus=unavailable\n");
745                                         ERR_print_errors(bio_err);
746                                         goto end;
747                                         }
748                                 BIO_printf(STDout,"Modulus=");
749 #ifndef OPENSSL_NO_RSA
750                                 if (pkey->type == EVP_PKEY_RSA)
751                                         BN_print(STDout,pkey->pkey.rsa->n);
752                                 else
753 #endif
754 #ifndef OPENSSL_NO_DSA
755                                 if (pkey->type == EVP_PKEY_DSA)
756                                         BN_print(STDout,pkey->pkey.dsa->pub_key);
757                                 else
758 #endif
759                                         BIO_printf(STDout,"Wrong Algorithm type");
760                                 BIO_printf(STDout,"\n");
761                                 EVP_PKEY_free(pkey);
762                                 }
763                         else
764                                 if (pubkey == i)
765                                 {
766                                 EVP_PKEY *pkey;
767
768                                 pkey=X509_get_pubkey(x);
769                                 if (pkey == NULL)
770                                         {
771                                         BIO_printf(bio_err,"Error getting public key\n");
772                                         ERR_print_errors(bio_err);
773                                         goto end;
774                                         }
775                                 PEM_write_bio_PUBKEY(STDout, pkey);
776                                 EVP_PKEY_free(pkey);
777                                 }
778                         else
779                                 if (C == i)
780                                 {
781                                 unsigned char *d;
782                                 char *m;
783                                 int y,z;
784
785                                 X509_NAME_oneline(X509_get_subject_name(x),
786                                         buf,sizeof buf);
787                                 BIO_printf(STDout,"/* subject:%s */\n",buf);
788                                 m=X509_NAME_oneline(
789                                         X509_get_issuer_name(x),buf,
790                                         sizeof buf);
791                                 BIO_printf(STDout,"/* issuer :%s */\n",buf);
792
793                                 z=i2d_X509(x,NULL);
794                                 m=OPENSSL_malloc(z);
795
796                                 d=(unsigned char *)m;
797                                 z=i2d_X509_NAME(X509_get_subject_name(x),&d);
798                                 BIO_printf(STDout,"unsigned char XXX_subject_name[%d]={\n",z);
799                                 d=(unsigned char *)m;
800                                 for (y=0; y<z; y++)
801                                         {
802                                         BIO_printf(STDout,"0x%02X,",d[y]);
803                                         if ((y & 0x0f) == 0x0f) BIO_printf(STDout,"\n");
804                                         }
805                                 if (y%16 != 0) BIO_printf(STDout,"\n");
806                                 BIO_printf(STDout,"};\n");
807
808                                 z=i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x),&d);
809                                 BIO_printf(STDout,"unsigned char XXX_public_key[%d]={\n",z);
810                                 d=(unsigned char *)m;
811                                 for (y=0; y<z; y++)
812                                         {
813                                         BIO_printf(STDout,"0x%02X,",d[y]);
814                                         if ((y & 0x0f) == 0x0f)
815                                                 BIO_printf(STDout,"\n");
816                                         }
817                                 if (y%16 != 0) BIO_printf(STDout,"\n");
818                                 BIO_printf(STDout,"};\n");
819
820                                 z=i2d_X509(x,&d);
821                                 BIO_printf(STDout,"unsigned char XXX_certificate[%d]={\n",z);
822                                 d=(unsigned char *)m;
823                                 for (y=0; y<z; y++)
824                                         {
825                                         BIO_printf(STDout,"0x%02X,",d[y]);
826                                         if ((y & 0x0f) == 0x0f)
827                                                 BIO_printf(STDout,"\n");
828                                         }
829                                 if (y%16 != 0) BIO_printf(STDout,"\n");
830                                 BIO_printf(STDout,"};\n");
831
832                                 OPENSSL_free(m);
833                                 }
834                         else if (text == i)
835                                 {
836                                 X509_print_ex(out,x,nmflag, certflag);
837                                 }
838                         else if (startdate == i)
839                                 {
840                                 BIO_puts(STDout,"notBefore=");
841                                 ASN1_TIME_print(STDout,X509_get_notBefore(x));
842                                 BIO_puts(STDout,"\n");
843                                 }
844                         else if (enddate == i)
845                                 {
846                                 BIO_puts(STDout,"notAfter=");
847                                 ASN1_TIME_print(STDout,X509_get_notAfter(x));
848                                 BIO_puts(STDout,"\n");
849                                 }
850                         else if (fingerprint == i)
851                                 {
852                                 int j;
853                                 unsigned int n;
854                                 unsigned char md[EVP_MAX_MD_SIZE];
855
856                                 if (!X509_digest(x,digest,md,&n))
857                                         {
858                                         BIO_printf(bio_err,"out of memory\n");
859                                         goto end;
860                                         }
861                                 BIO_printf(STDout,"%s Fingerprint=",
862                                                 OBJ_nid2sn(EVP_MD_type(digest)));
863                                 for (j=0; j<(int)n; j++)
864                                         {
865                                         BIO_printf(STDout,"%02X%c",md[j],
866                                                 (j+1 == (int)n)
867                                                 ?'\n':':');
868                                         }
869                                 }
870
871                         /* should be in the library */
872                         else if ((sign_flag == i) && (x509req == 0))
873                                 {
874                                 BIO_printf(bio_err,"Getting Private key\n");
875                                 if (Upkey == NULL)
876                                         {
877                                         Upkey=load_key(bio_err,
878                                                 keyfile, keyformat, 0,
879                                                 passin, e, "Private key");
880                                         if (Upkey == NULL) goto end;
881                                         }
882 #ifndef OPENSSL_NO_DSA
883                                 if (Upkey->type == EVP_PKEY_DSA)
884                                         digest=EVP_dss1();
885 #endif
886 #ifndef OPENSSL_NO_ECDSA
887                                 if (Upkey->type == EVP_PKEY_EC)
888                                         digest=EVP_ecdsa();
889 #endif
890
891                                 assert(need_rand);
892                                 if (!sign(x,Upkey,days,clrext,digest,
893                                                  extconf, extsect)) goto end;
894                                 }
895                         else if (CA_flag == i)
896                                 {
897                                 BIO_printf(bio_err,"Getting CA Private Key\n");
898                                 if (CAkeyfile != NULL)
899                                         {
900                                         CApkey=load_key(bio_err,
901                                                 CAkeyfile, CAkeyformat,
902                                                 0, passin, e,
903                                                 "CA Private Key");
904                                         if (CApkey == NULL) goto end;
905                                         }
906 #ifndef OPENSSL_NO_DSA
907                                 if (CApkey->type == EVP_PKEY_DSA)
908                                         digest=EVP_dss1();
909 #endif
910 #ifndef OPENSSL_NO_ECDSA
911                                 if (CApkey->type == EVP_PKEY_EC)
912                                         digest = EVP_ecdsa();
913 #endif
914                                 
915                                 assert(need_rand);
916                                 if (!x509_certify(ctx,CAfile,digest,x,xca,
917                                         CApkey, CAserial,CA_createserial,days, clrext,
918                                         extconf, extsect, sno))
919                                         goto end;
920                                 }
921                         else if (x509req == i)
922                                 {
923                                 EVP_PKEY *pk;
924
925                                 BIO_printf(bio_err,"Getting request Private Key\n");
926                                 if (keyfile == NULL)
927                                         {
928                                         BIO_printf(bio_err,"no request key file specified\n");
929                                         goto end;
930                                         }
931                                 else
932                                         {
933                                         pk=load_key(bio_err,
934                                                 keyfile, FORMAT_PEM, 0,
935                                                 passin, e, "request key");
936                                         if (pk == NULL) goto end;
937                                         }
938
939                                 BIO_printf(bio_err,"Generating certificate request\n");
940
941 #ifndef OPENSSL_NO_DSA
942                                 if (pk->type == EVP_PKEY_DSA)
943                                         digest=EVP_dss1();
944 #endif
945 #ifndef OPENSSL_NO_ECDSA
946                                 if (pk->type == EVP_PKEY_EC)
947                                         digest=EVP_ecdsa();
948 #endif
949
950                                 rq=X509_to_X509_REQ(x,pk,digest);
951                                 EVP_PKEY_free(pk);
952                                 if (rq == NULL)
953                                         {
954                                         ERR_print_errors(bio_err);
955                                         goto end;
956                                         }
957                                 if (!noout)
958                                         {
959                                         X509_REQ_print(out,rq);
960                                         PEM_write_bio_X509_REQ(out,rq);
961                                         }
962                                 noout=1;
963                                 }
964                         else if (ocspid == i)
965                                 {
966                                 X509_ocspid_print(out, x);
967                                 }
968                         }
969                 }
970
971         if (checkend)
972                 {
973                 time_t tnow=time(NULL);
974
975                 if (ASN1_UTCTIME_cmp_time_t(X509_get_notAfter(x), tnow+checkoffset) == -1)
976                         {
977                         BIO_printf(out,"Certificate will expire\n");
978                         ret=1;
979                         }
980                 else
981                         {
982                         BIO_printf(out,"Certificate will not expire\n");
983                         ret=0;
984                         }
985                 goto end;
986                 }
987
988         if (noout)
989                 {
990                 ret=0;
991                 goto end;
992                 }
993
994         if      (outformat == FORMAT_ASN1)
995                 i=i2d_X509_bio(out,x);
996         else if (outformat == FORMAT_PEM)
997                 {
998                 if (trustout) i=PEM_write_bio_X509_AUX(out,x);
999                 else i=PEM_write_bio_X509(out,x);
1000                 }
1001         else if (outformat == FORMAT_NETSCAPE)
1002                 {
1003                 ASN1_HEADER ah;
1004                 ASN1_OCTET_STRING os;
1005
1006                 os.data=(unsigned char *)NETSCAPE_CERT_HDR;
1007                 os.length=strlen(NETSCAPE_CERT_HDR);
1008                 ah.header= &os;
1009                 ah.data=(char *)x;
1010                 ah.meth=X509_asn1_meth();
1011
1012                 /* no macro for this one yet */
1013                 i=ASN1_i2d_bio(i2d_ASN1_HEADER,out,(unsigned char *)&ah);
1014                 }
1015         else    {
1016                 BIO_printf(bio_err,"bad output format specified for outfile\n");
1017                 goto end;
1018                 }
1019         if (!i)
1020                 {
1021                 BIO_printf(bio_err,"unable to write certificate\n");
1022                 ERR_print_errors(bio_err);
1023                 goto end;
1024                 }
1025         ret=0;
1026 end:
1027         if (need_rand)
1028                 app_RAND_write_file(NULL, bio_err);
1029         OBJ_cleanup();
1030         NCONF_free(extconf);
1031         BIO_free_all(out);
1032         BIO_free_all(STDout);
1033         X509_STORE_free(ctx);
1034         X509_REQ_free(req);
1035         X509_free(x);
1036         X509_free(xca);
1037         EVP_PKEY_free(Upkey);
1038         EVP_PKEY_free(CApkey);
1039         X509_REQ_free(rq);
1040         ASN1_INTEGER_free(sno);
1041         sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free);
1042         sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free);
1043         if (passin) OPENSSL_free(passin);
1044         apps_shutdown();
1045         OPENSSL_EXIT(ret);
1046         }
1047
1048 static ASN1_INTEGER *x509_load_serial(char *CAfile, char *serialfile, int create)
1049         {
1050         char *buf = NULL, *p;
1051         ASN1_INTEGER *bs = NULL;
1052         BIGNUM *serial = NULL;
1053         size_t len;
1054
1055         len = ((serialfile == NULL)
1056                 ?(strlen(CAfile)+strlen(POSTFIX)+1)
1057                 :(strlen(serialfile)))+1;
1058         buf=OPENSSL_malloc(len);
1059         if (buf == NULL) { BIO_printf(bio_err,"out of mem\n"); goto end; }
1060         if (serialfile == NULL)
1061                 {
1062                 BUF_strlcpy(buf,CAfile,len);
1063                 for (p=buf; *p; p++)
1064                         if (*p == '.')
1065                                 {
1066                                 *p='\0';
1067                                 break;
1068                                 }
1069                 BUF_strlcat(buf,POSTFIX,len);
1070                 }
1071         else
1072                 BUF_strlcpy(buf,serialfile,len);
1073
1074         serial = load_serial(buf, create, NULL);
1075         if (serial == NULL) goto end;
1076
1077         if (!BN_add_word(serial,1))
1078                 { BIO_printf(bio_err,"add_word failure\n"); goto end; }
1079
1080         if (!save_serial(buf, NULL, serial, &bs)) goto end;
1081
1082  end:
1083         if (buf) OPENSSL_free(buf);
1084         BN_free(serial);
1085         return bs;
1086         }
1087
1088 static int x509_certify(X509_STORE *ctx, char *CAfile, const EVP_MD *digest,
1089              X509 *x, X509 *xca, EVP_PKEY *pkey, char *serialfile, int create,
1090              int days, int clrext, CONF *conf, char *section, ASN1_INTEGER *sno)
1091         {
1092         int ret=0;
1093         ASN1_INTEGER *bs=NULL;
1094         X509_STORE_CTX xsc;
1095         EVP_PKEY *upkey;
1096
1097         upkey = X509_get_pubkey(xca);
1098         EVP_PKEY_copy_parameters(upkey,pkey);
1099         EVP_PKEY_free(upkey);
1100
1101         if(!X509_STORE_CTX_init(&xsc,ctx,x,NULL))
1102                 {
1103                 BIO_printf(bio_err,"Error initialising X509 store\n");
1104                 goto end;
1105                 }
1106         if (sno) bs = sno;
1107         else if (!(bs = x509_load_serial(CAfile, serialfile, create)))
1108                 goto end;
1109
1110 /*      if (!X509_STORE_add_cert(ctx,x)) goto end;*/
1111
1112         /* NOTE: this certificate can/should be self signed, unless it was
1113          * a certificate request in which case it is not. */
1114         X509_STORE_CTX_set_cert(&xsc,x);
1115         if (!reqfile && !X509_verify_cert(&xsc))
1116                 goto end;
1117
1118         if (!X509_check_private_key(xca,pkey))
1119                 {
1120                 BIO_printf(bio_err,"CA certificate and CA private key do not match\n");
1121                 goto end;
1122                 }
1123
1124         if (!X509_set_issuer_name(x,X509_get_subject_name(xca))) goto end;
1125         if (!X509_set_serialNumber(x,bs)) goto end;
1126
1127         if (X509_gmtime_adj(X509_get_notBefore(x),0L) == NULL)
1128                 goto end;
1129
1130         /* hardwired expired */
1131         if (X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days) == NULL)
1132                 goto end;
1133
1134         if (clrext)
1135                 {
1136                 while (X509_get_ext_count(x) > 0) X509_delete_ext(x, 0);
1137                 }
1138
1139         if (conf)
1140                 {
1141                 X509V3_CTX ctx2;
1142                 X509_set_version(x,2); /* version 3 certificate */
1143                 X509V3_set_ctx(&ctx2, xca, x, NULL, NULL, 0);
1144                 X509V3_set_nconf(&ctx2, conf);
1145                 if (!X509V3_EXT_add_nconf(conf, &ctx2, section, x)) goto end;
1146                 }
1147
1148         if (!X509_sign(x,pkey,digest)) goto end;
1149         ret=1;
1150 end:
1151         X509_STORE_CTX_cleanup(&xsc);
1152         if (!ret)
1153                 ERR_print_errors(bio_err);
1154         if (!sno) ASN1_INTEGER_free(bs);
1155         return ret;
1156         }
1157
1158 static int MS_CALLBACK callb(int ok, X509_STORE_CTX *ctx)
1159         {
1160         int err;
1161         X509 *err_cert;
1162
1163         /* it is ok to use a self signed certificate
1164          * This case will catch both the initial ok == 0 and the
1165          * final ok == 1 calls to this function */
1166         err=X509_STORE_CTX_get_error(ctx);
1167         if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
1168                 return 1;
1169
1170         /* BAD we should have gotten an error.  Normally if everything
1171          * worked X509_STORE_CTX_get_error(ctx) will still be set to
1172          * DEPTH_ZERO_SELF_.... */
1173         if (ok)
1174                 {
1175                 BIO_printf(bio_err,"error with certificate to be certified - should be self signed\n");
1176                 return 0;
1177                 }
1178         else
1179                 {
1180                 err_cert=X509_STORE_CTX_get_current_cert(ctx);
1181                 print_name(bio_err, NULL, X509_get_subject_name(err_cert),0);
1182                 BIO_printf(bio_err,"error with certificate - error %d at depth %d\n%s\n",
1183                         err,X509_STORE_CTX_get_error_depth(ctx),
1184                         X509_verify_cert_error_string(err));
1185                 return 1;
1186                 }
1187         }
1188
1189 /* self sign */
1190 static int sign(X509 *x, EVP_PKEY *pkey, int days, int clrext, const EVP_MD *digest, 
1191                                                 CONF *conf, char *section)
1192         {
1193
1194         EVP_PKEY *pktmp;
1195
1196         pktmp = X509_get_pubkey(x);
1197         EVP_PKEY_copy_parameters(pktmp,pkey);
1198         EVP_PKEY_save_parameters(pktmp,1);
1199         EVP_PKEY_free(pktmp);
1200
1201         if (!X509_set_issuer_name(x,X509_get_subject_name(x))) goto err;
1202         if (X509_gmtime_adj(X509_get_notBefore(x),0) == NULL) goto err;
1203
1204         /* Lets just make it 12:00am GMT, Jan 1 1970 */
1205         /* memcpy(x->cert_info->validity->notBefore,"700101120000Z",13); */
1206         /* 28 days to be certified */
1207
1208         if (X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days) == NULL)
1209                 goto err;
1210
1211         if (!X509_set_pubkey(x,pkey)) goto err;
1212         if (clrext)
1213                 {
1214                 while (X509_get_ext_count(x) > 0) X509_delete_ext(x, 0);
1215                 }
1216         if (conf)
1217                 {
1218                 X509V3_CTX ctx;
1219                 X509_set_version(x,2); /* version 3 certificate */
1220                 X509V3_set_ctx(&ctx, x, x, NULL, NULL, 0);
1221                 X509V3_set_nconf(&ctx, conf);
1222                 if (!X509V3_EXT_add_nconf(conf, &ctx, section, x)) goto err;
1223                 }
1224         if (!X509_sign(x,pkey,digest)) goto err;
1225         return 1;
1226 err:
1227         ERR_print_errors(bio_err);
1228         return 0;
1229         }
1230
1231 static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt)
1232 {
1233         int id, i, idret;
1234         char *pname;
1235         id = X509_PURPOSE_get_id(pt);
1236         pname = X509_PURPOSE_get0_name(pt);
1237         for (i = 0; i < 2; i++)
1238                 {
1239                 idret = X509_check_purpose(cert, id, i);
1240                 BIO_printf(bio, "%s%s : ", pname, i ? " CA" : ""); 
1241                 if (idret == 1) BIO_printf(bio, "Yes\n");
1242                 else if (idret == 0) BIO_printf(bio, "No\n");
1243                 else BIO_printf(bio, "Yes (WARNING code=%d)\n", idret);
1244                 }
1245         return 1;
1246 }