This commit was generated by cvs2svn to track changes on a CVS vendor
[openssl.git] / apps / req.c
1 /* apps/req.c */
2 /* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <time.h>
62 #include <string.h>
63 #ifdef WIN16
64 #define APPS_WIN16
65 #endif
66 #include "apps.h"
67 #include "bio.h"
68 #include "evp.h"
69 #include "rand.h"
70 #include "conf.h"
71 #include "err.h"
72 #include "asn1.h"
73 #include "x509.h"
74 #include "objects.h"
75 #include "pem.h"
76
77 #define SECTION         "req"
78
79 #define BITS            "default_bits"
80 #define KEYFILE         "default_keyfile"
81 #define DISTINGUISHED_NAME      "distinguished_name"
82 #define ATTRIBUTES      "attributes"
83
84 #define DEFAULT_KEY_LENGTH      512
85 #define MIN_KEY_LENGTH          384
86
87 #undef PROG
88 #define PROG    req_main
89
90 /* -inform arg  - input format - default PEM (one of DER, TXT or PEM)
91  * -outform arg - output format - default PEM
92  * -in arg      - input file - default stdin
93  * -out arg     - output file - default stdout
94  * -verify      - check request signature
95  * -noout       - don't print stuff out.
96  * -text        - print out human readable text.
97  * -nodes       - no des encryption
98  * -config file - Load configuration file.
99  * -key file    - make a request using key in file (or use it for verification).
100  * -keyform     - key file format.
101  * -newkey      - make a key and a request.
102  * -modulus     - print RSA modulus.
103  * -x509        - output a self signed X509 structure instead.
104  * -asn1-kludge - output new certificate request in a format that some CA's
105  *                require.  This format is wrong
106  */
107
108 #ifndef NOPROTO
109 static int make_REQ(X509_REQ *req,EVP_PKEY *pkey,int attribs);
110 static int add_attribute_object(STACK *n, char *text, char *def, 
111         char *value, int nid,int min,int max);
112 static int add_DN_object(X509_NAME *n, char *text, char *def, char *value,
113         int nid,int min,int max);
114 static void MS_CALLBACK req_cb(int p,int n);
115 static int req_fix_data(int nid,int *type,int len,int min,int max);
116 #else
117 static int make_REQ();
118 static int add_attribute_object();
119 static int add_DN_object();
120 static void MS_CALLBACK req_cb();
121 static int req_fix_data();
122 #endif
123
124 #ifndef MONOLITH
125 static char *default_config_file=NULL;
126 static LHASH *config=NULL;
127 #endif
128 static LHASH *req_conf=NULL;
129
130 #define TYPE_RSA        1
131 #define TYPE_DSA        2
132 #define TYPE_DH         3
133
134 int MAIN(argc, argv)
135 int argc;
136 char **argv;
137         {
138         DSA *dsa_params=NULL;
139         int ex=1,x509=0,days=30;
140         X509 *x509ss=NULL;
141         X509_REQ *req=NULL;
142         EVP_PKEY *pkey=NULL;
143         int i,badops=0,newreq=0,newkey= -1,pkey_type=0;
144         BIO *in=NULL,*out=NULL;
145         int informat,outformat,verify=0,noout=0,text=0,keyform=FORMAT_PEM;
146         int nodes=0,kludge=0;
147         char *infile,*outfile,*prog,*keyfile=NULL,*template=NULL,*keyout=NULL;
148         EVP_CIPHER *cipher=NULL;
149         int modulus=0;
150         char *p;
151         EVP_MD *md_alg=NULL,*digest=EVP_md5();
152 #ifndef MONOLITH
153         MS_STATIC char config_name[256];
154 #endif
155
156 #ifndef NO_DES
157         cipher=EVP_des_ede3_cbc();
158 #endif
159         apps_startup();
160
161         if (bio_err == NULL)
162                 if ((bio_err=BIO_new(BIO_s_file())) != NULL)
163                         BIO_set_fp(bio_err,stderr,BIO_NOCLOSE);
164
165         infile=NULL;
166         outfile=NULL;
167         informat=FORMAT_PEM;
168         outformat=FORMAT_PEM;
169
170         prog=argv[0];
171         argc--;
172         argv++;
173         while (argc >= 1)
174                 {
175                 if      (strcmp(*argv,"-inform") == 0)
176                         {
177                         if (--argc < 1) goto bad;
178                         informat=str2fmt(*(++argv));
179                         }
180                 else if (strcmp(*argv,"-outform") == 0)
181                         {
182                         if (--argc < 1) goto bad;
183                         outformat=str2fmt(*(++argv));
184                         }
185                 else if (strcmp(*argv,"-key") == 0)
186                         {
187                         if (--argc < 1) goto bad;
188                         keyfile= *(++argv);
189                         }
190                 else if (strcmp(*argv,"-new") == 0)
191                         {
192                         pkey_type=TYPE_RSA;
193                         newreq=1;
194                         }
195                 else if (strcmp(*argv,"-config") == 0)
196                         {       
197                         if (--argc < 1) goto bad;
198                         template= *(++argv);
199                         }
200                 else if (strcmp(*argv,"-keyform") == 0)
201                         {
202                         if (--argc < 1) goto bad;
203                         keyform=str2fmt(*(++argv));
204                         }
205                 else if (strcmp(*argv,"-in") == 0)
206                         {
207                         if (--argc < 1) goto bad;
208                         infile= *(++argv);
209                         }
210                 else if (strcmp(*argv,"-out") == 0)
211                         {
212                         if (--argc < 1) goto bad;
213                         outfile= *(++argv);
214                         }
215                 else if (strcmp(*argv,"-keyout") == 0)
216                         {
217                         if (--argc < 1) goto bad;
218                         keyout= *(++argv);
219                         }
220                 else if (strcmp(*argv,"-newkey") == 0)
221                         {
222                         if (--argc < 1) goto bad;
223                         p= *(++argv);
224                         if ((strncmp("rsa:",p,4) == 0) ||
225                                 ((p[0] >= '0') && (p[0] <= '9')))
226                                 {
227                                 pkey_type=TYPE_RSA;
228                                 p+=4;
229                                 newkey= atoi(p);
230                                 }
231                         else if (strncmp("dsa:",p,4) == 0)
232                                 {
233                                 X509 *xtmp=NULL;
234                                 EVP_PKEY *dtmp;
235
236                                 pkey_type=TYPE_DSA;
237                                 p+=4;
238                                 if ((in=BIO_new_file(p,"r")) == NULL)
239                                         {
240                                         perror(p);
241                                         goto end;
242                                         }
243                                 if ((dsa_params=PEM_read_bio_DSAparams(in,NULL,NULL)) == NULL)
244                                         {
245                                         ERR_clear_error();
246                                         BIO_reset(in);
247                                         if ((xtmp=PEM_read_bio_X509(in,NULL,NULL)) == NULL)
248                                                 {
249                                                 BIO_printf(bio_err,"unable to load DSA parameters from file\n");
250                                                 goto end;
251                                                 }
252                                         dtmp=X509_get_pubkey(xtmp);
253                                         if (dtmp->type == EVP_PKEY_DSA)
254                                                 dsa_params=DSAparams_dup(dtmp->pkey.dsa);
255                                         X509_free(xtmp);
256                                         if (dsa_params == NULL)
257                                                 {
258                                                 BIO_printf(bio_err,"Certificate does not contain DSA parameters\n");
259                                                 goto end;
260                                                 }
261                                         
262                                         }
263                                 BIO_free(in);
264                                 newkey=BN_num_bits(dsa_params->p);
265                                 in=NULL;
266                                 }
267                         else if (strncmp("dh:",p,4) == 0)
268                                 {
269                                 pkey_type=TYPE_DH;
270                                 p+=3;
271                                 }
272                         else
273                                 pkey_type=TYPE_RSA;
274
275                         newreq=1;
276                         }
277                 else if (strcmp(*argv,"-modulus") == 0)
278                         modulus=1;
279                 else if (strcmp(*argv,"-verify") == 0)
280                         verify=1;
281                 else if (strcmp(*argv,"-nodes") == 0)
282                         nodes=1;
283                 else if (strcmp(*argv,"-noout") == 0)
284                         noout=1;
285                 else if (strcmp(*argv,"-text") == 0)
286                         text=1;
287                 else if (strcmp(*argv,"-x509") == 0)
288                         x509=1;
289                 else if (strcmp(*argv,"-asn1-kludge") == 0)
290                         kludge=1;
291                 else if (strcmp(*argv,"-no-asn1-kludge") == 0)
292                         kludge=0;
293                 else if (strcmp(*argv,"-days") == 0)
294                         {
295                         if (--argc < 1) goto bad;
296                         days= atoi(*(++argv));
297                         if (days == 0) days=30;
298                         }
299                 else if ((md_alg=EVP_get_digestbyname(&((*argv)[1]))) != NULL)
300                         {
301                         /* ok */
302                         digest=md_alg;
303                         }
304                 else
305
306                         {
307                         BIO_printf(bio_err,"unknown option %s\n",*argv);
308                         badops=1;
309                         break;
310                         }
311                 argc--;
312                 argv++;
313                 }
314
315         if (badops)
316                 {
317 bad:
318                 BIO_printf(bio_err,"%s [options] <infile >outfile\n",prog);
319                 BIO_printf(bio_err,"where options  are\n");
320                 BIO_printf(bio_err," -inform arg    input format - one of DER TXT PEM\n");
321                 BIO_printf(bio_err," -outform arg   output format - one of DER TXT PEM\n");
322                 BIO_printf(bio_err," -in arg        inout file\n");
323                 BIO_printf(bio_err," -out arg       output file\n");
324                 BIO_printf(bio_err," -text          text form of request\n");
325                 BIO_printf(bio_err," -noout         do not output REQ\n");
326                 BIO_printf(bio_err," -verify        verify signature on REQ\n");
327                 BIO_printf(bio_err," -modulus       RSA modulus\n");
328                 BIO_printf(bio_err," -nodes         don't encrypt the output key\n");
329                 BIO_printf(bio_err," -key file  use the private key contained in file\n");
330                 BIO_printf(bio_err," -keyform arg   key file format\n");
331                 BIO_printf(bio_err," -keyout arg    file to send the key to\n");
332                 BIO_printf(bio_err," -newkey rsa:bits generate a new RSA key of 'bits' in size\n");
333                 BIO_printf(bio_err," -newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'\n");
334
335                 BIO_printf(bio_err," -[digest]      Digest to sign with (md5, sha1, md2, mdc2)\n");
336                 BIO_printf(bio_err," -config file   request templace file.\n");
337                 BIO_printf(bio_err," -new           new request.\n");
338                 BIO_printf(bio_err," -x509          output a x509 structure instead of a cert. req.\n");
339                 BIO_printf(bio_err," -days          number of days a x509 generated by -x509 is valid for.\n");
340                 BIO_printf(bio_err," -asn1-kludge   Output the 'request' in a format that is wrong but some CA's\n");
341                 BIO_printf(bio_err,"                have been reported as requiring\n");
342                 BIO_printf(bio_err,"                [ It is now always turned on but can be turned off with -no-asn1-kludge ]\n");
343                 goto end;
344                 }
345
346         ERR_load_crypto_strings();
347
348 #ifndef MONOLITH
349         /* Lets load up our environment a little */
350         p=getenv("SSLEAY_CONF");
351         if (p == NULL)
352                 {
353                 strcpy(config_name,X509_get_default_cert_area());
354                 strcat(config_name,"/lib/");
355                 strcat(config_name,SSLEAY_CONF);
356                 p=config_name;
357                 }
358         default_config_file=p;
359         config=CONF_load(config,p,NULL);
360 #endif
361
362         if (template != NULL)
363                 {
364                 long errline;
365
366                 BIO_printf(bio_err,"Using configuration from %s\n",template);
367                 req_conf=CONF_load(NULL,template,&errline);
368                 if (req_conf == NULL)
369                         {
370                         BIO_printf(bio_err,"error on line %ld of %s\n",errline,template);
371                         goto end;
372                         }
373                 }
374         else
375                 {
376                 req_conf=config;
377                 BIO_printf(bio_err,"Using configuration from %s\n",
378                         default_config_file);
379                 if (req_conf == NULL)
380                         {
381                         BIO_printf(bio_err,"Unable to load config info\n");
382                         }
383                 }
384
385         if ((md_alg == NULL) &&
386                 ((p=CONF_get_string(req_conf,SECTION,"default_md")) != NULL))
387                 {
388                 if ((md_alg=EVP_get_digestbyname(p)) != NULL)
389                         digest=md_alg;
390                 }
391
392         in=BIO_new(BIO_s_file());
393         out=BIO_new(BIO_s_file());
394         if ((in == NULL) || (out == NULL))
395                 goto end;
396
397         if (keyfile != NULL)
398                 {
399                 if (BIO_read_filename(in,keyfile) <= 0)
400                         {
401                         perror(keyfile);
402                         goto end;
403                         }
404
405 /*              if (keyform == FORMAT_ASN1)
406                         rsa=d2i_RSAPrivateKey_bio(in,NULL);
407                 else */
408                 if (keyform == FORMAT_PEM)
409                         pkey=PEM_read_bio_PrivateKey(in,NULL,NULL);
410                 else
411                         {
412                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
413                         goto end;
414                         }
415
416                 if (pkey == NULL)
417                         {
418                         BIO_printf(bio_err,"unable to load Private key\n");
419                         goto end;
420                         }
421                 }
422
423         if (newreq && (pkey == NULL))
424                 {
425                 char *randfile;
426                 char buffer[200];
427
428                 if ((randfile=CONF_get_string(req_conf,SECTION,"RANDFILE")) == NULL)
429                         randfile=RAND_file_name(buffer,200);
430 #ifdef WINDOWS
431                 BIO_printf(bio_err,"Loading 'screen' into random state -");
432                 BIO_flush(bio_err);
433                 RAND_screen();
434                 BIO_printf(bio_err," done\n");
435 #endif
436                 if ((randfile == NULL) || !RAND_load_file(randfile,1024L*1024L))
437                         {
438                         BIO_printf(bio_err,"unable to load 'random state'\n");
439                         BIO_printf(bio_err,"What this means is that the random number generator has not been seeded\n");
440                         BIO_printf(bio_err,"with much random data.\n");
441                         BIO_printf(bio_err,"Consider setting the RANDFILE environment variable to point at a file that\n");
442                         BIO_printf(bio_err,"'random' data can be kept in.\n");
443                         }
444                 if (newkey <= 0)
445                         {
446                         newkey=(int)CONF_get_number(req_conf,SECTION,BITS);
447                         if (newkey <= 0)
448                                 newkey=DEFAULT_KEY_LENGTH;
449                         }
450
451                 if (newkey < MIN_KEY_LENGTH)
452                         {
453                         BIO_printf(bio_err,"private key length is too short,\n");
454                         BIO_printf(bio_err,"it needs to be at least %d bits, not %d\n",MIN_KEY_LENGTH,newkey);
455                         goto end;
456                         }
457                 BIO_printf(bio_err,"Generating a %d bit %s private key\n",
458                         newkey,(pkey_type == TYPE_RSA)?"RSA":"DSA");
459
460                 if ((pkey=EVP_PKEY_new()) == NULL) goto end;
461
462 #ifndef NO_RSA
463                 if (pkey_type == TYPE_RSA)
464                         {
465                         if (!EVP_PKEY_assign_RSA(pkey,
466                                 RSA_generate_key(newkey,0x10001,req_cb)))
467                                 goto end;
468                         }
469                 else
470 #endif
471 #ifndef NO_DSA
472                         if (pkey_type == TYPE_DSA)
473                         {
474                         if (!DSA_generate_key(dsa_params)) goto end;
475                         if (!EVP_PKEY_assign_DSA(pkey,dsa_params)) goto end;
476                         dsa_params=NULL;
477                         }
478 #endif
479
480                 if ((randfile == NULL) || (RAND_write_file(randfile) == 0))
481                         BIO_printf(bio_err,"unable to write 'random state'\n");
482
483                 if (pkey == NULL) goto end;
484
485                 if (keyout == NULL)
486                         keyout=CONF_get_string(req_conf,SECTION,KEYFILE);
487
488                 if (keyout == NULL)
489                         {
490                         BIO_printf(bio_err,"writing new private key to stdout\n");
491                         BIO_set_fp(out,stdout,BIO_NOCLOSE);
492                         }
493                 else
494                         {
495                         BIO_printf(bio_err,"writing new private key to '%s'\n",keyout);
496                         if (BIO_write_filename(out,keyout) <= 0)
497                                 {
498                                 perror(keyout);
499                                 goto end;
500                                 }
501                         }
502
503                 p=CONF_get_string(req_conf,SECTION,"encrypt_rsa_key");
504                 if (p == NULL)
505                         p=CONF_get_string(req_conf,SECTION,"encrypt_key");
506                 if ((p != NULL) && (strcmp(p,"no") == 0))
507                         cipher=NULL;
508                 if (nodes) cipher=NULL;
509                 
510                 i=0;
511 loop:
512                 if (!PEM_write_bio_PrivateKey(out,pkey,cipher,
513                         NULL,0,NULL))
514                         {
515                         if ((ERR_GET_REASON(ERR_peek_error()) ==
516                                 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3))
517                                 {
518                                 ERR_clear_error();
519                                 i++;
520                                 goto loop;
521                                 }
522                         goto end;
523                         }
524                 BIO_printf(bio_err,"-----\n");
525                 }
526
527         if (!newreq)
528                 {
529                 /* Since we are using a pre-existing certificate
530                  * request, the kludge 'format' info should not be
531                  * changed. */
532                 kludge= -1;
533                 if (infile == NULL)
534                         BIO_set_fp(in,stdin,BIO_NOCLOSE);
535                 else
536                         {
537                         if (BIO_read_filename(in,infile) <= 0)
538                                 {
539                                 perror(infile);
540                                 goto end;
541                                 }
542                         }
543
544                 if      (informat == FORMAT_ASN1)
545                         req=d2i_X509_REQ_bio(in,NULL);
546                 else if (informat == FORMAT_PEM)
547                         req=PEM_read_bio_X509_REQ(in,NULL,NULL);
548                 else
549                         {
550                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
551                         goto end;
552                         }
553                 if (req == NULL)
554                         {
555                         BIO_printf(bio_err,"unable to load X509 request\n");
556                         goto end;
557                         }
558                 }
559
560         if (newreq || x509)
561                 {
562                 if (pkey->type == EVP_PKEY_DSA)
563                         digest=EVP_dss1();
564
565                 if (pkey == NULL)
566                         {
567                         BIO_printf(bio_err,"you need to specify a private key\n");
568                         goto end;
569                         }
570                 if (req == NULL)
571                         {
572                         req=X509_REQ_new();
573                         if (req == NULL)
574                                 {
575                                 goto end;
576                                 }
577
578                         i=make_REQ(req,pkey,!x509);
579                         if (kludge >= 0)
580                                 req->req_info->req_kludge=kludge;
581                         if (!i)
582                                 {
583                                 BIO_printf(bio_err,"problems making Certificate Request\n");
584                                 goto end;
585                                 }
586                         }
587                 if (x509)
588                         {
589                         if ((x509ss=X509_new()) == NULL) goto end;
590
591                         /* don't set the version number, for starters
592                          * the field is null and second, null is v0 
593                          * if (!ASN1_INTEGER_set(ci->version,0L)) goto end;
594                          */
595                         ASN1_INTEGER_set(X509_get_serialNumber(x509ss),0L);
596
597                         X509_set_issuer_name(x509ss,
598                                 X509_REQ_get_subject_name(req));
599                         X509_gmtime_adj(X509_get_notBefore(x509ss),0);
600                         X509_gmtime_adj(X509_get_notAfter(x509ss),
601                                 (long)60*60*24*days);
602                         X509_set_subject_name(x509ss,
603                                 X509_REQ_get_subject_name(req));
604                         X509_set_pubkey(x509ss,X509_REQ_get_pubkey(req));
605
606                         if (!(i=X509_sign(x509ss,pkey,digest)))
607                                 goto end;
608                         }
609                 else
610                         {
611                         if (!(i=X509_REQ_sign(req,pkey,digest)))
612                                 goto end;
613                         }
614                 }
615
616         if (verify && !x509)
617                 {
618                 int tmp=0;
619
620                 if (pkey == NULL)
621                         {
622                         pkey=X509_REQ_get_pubkey(req);
623                         tmp=1;
624                         if (pkey == NULL) goto end;
625                         }
626
627                 i=X509_REQ_verify(req,pkey);
628                 if (tmp) pkey=NULL;
629
630                 if (i < 0)
631                         {
632                         goto end;
633                         }
634                 else if (i == 0)
635                         {
636                         BIO_printf(bio_err,"verify failure\n");
637                         }
638                 else /* if (i > 0) */
639                         BIO_printf(bio_err,"verify OK\n");
640                 }
641
642         if (noout && !text && !modulus)
643                 {
644                 ex=0;
645                 goto end;
646                 }
647
648         if (outfile == NULL)
649                 BIO_set_fp(out,stdout,BIO_NOCLOSE);
650         else
651                 {
652                 if ((keyout != NULL) && (strcmp(outfile,keyout) == 0))
653                         i=(int)BIO_append_filename(out,outfile);
654                 else
655                         i=(int)BIO_write_filename(out,outfile);
656                 if (!i)
657                         {
658                         perror(outfile);
659                         goto end;
660                         }
661                 }
662
663         if (text)
664                 {
665                 if (x509)
666                         X509_print(out,x509ss);
667                 else    
668                         X509_REQ_print(out,req);
669                 }
670
671         if (modulus)
672                 {
673                 EVP_PKEY *pubkey;
674
675                 if (x509)
676                         pubkey=X509_get_pubkey(x509ss);
677                 else
678                         pubkey=X509_REQ_get_pubkey(req);
679                 if (pubkey == NULL)
680                         {
681                         fprintf(stdout,"Modulus=unavailable\n");
682                         goto end; 
683                         }
684                 fprintf(stdout,"Modulus=");
685                 if (pubkey->type == EVP_PKEY_RSA)
686                         BN_print(out,pubkey->pkey.rsa->n);
687                 else
688                         fprintf(stdout,"Wrong Algorithm type");
689                 fprintf(stdout,"\n");
690                 }
691
692         if (!noout && !x509)
693                 {
694                 if      (outformat == FORMAT_ASN1)
695                         i=i2d_X509_REQ_bio(out,req);
696                 else if (outformat == FORMAT_PEM)
697                         i=PEM_write_bio_X509_REQ(out,req);
698                 else    {
699                         BIO_printf(bio_err,"bad output format specified for outfile\n");
700                         goto end;
701                         }
702                 if (!i)
703                         {
704                         BIO_printf(bio_err,"unable to write X509 request\n");
705                         goto end;
706                         }
707                 }
708         if (!noout && x509 && (x509ss != NULL))
709                 {
710                 if      (outformat == FORMAT_ASN1)
711                         i=i2d_X509_bio(out,x509ss);
712                 else if (outformat == FORMAT_PEM)
713                         i=PEM_write_bio_X509(out,x509ss);
714                 else    {
715                         BIO_printf(bio_err,"bad output format specified for outfile\n");
716                         goto end;
717                         }
718                 if (!i)
719                         {
720                         BIO_printf(bio_err,"unable to write X509 certificate\n");
721                         goto end;
722                         }
723                 }
724         ex=0;
725 end:
726         if (ex)
727                 {
728                 ERR_print_errors(bio_err);
729                 }
730         if ((req_conf != NULL) && (req_conf != config)) CONF_free(req_conf);
731         if (in != NULL) BIO_free(in);
732         if (out != NULL) BIO_free(out);
733         if (pkey != NULL) EVP_PKEY_free(pkey);
734         if (req != NULL) X509_REQ_free(req);
735         if (x509ss != NULL) X509_free(x509ss);
736         if (dsa_params != NULL) DSA_free(dsa_params);
737         EXIT(ex);
738         }
739
740 static int make_REQ(req,pkey,attribs)
741 X509_REQ *req;
742 EVP_PKEY *pkey;
743 int attribs;
744         {
745         int ret=0,i,j;
746         unsigned char *p;
747         X509_REQ_INFO *ri;
748         char buf[100];
749         int nid,min,max;
750         char *type,*def,*tmp,*value,*tmp_attr;
751         STACK *sk,*attr=NULL;
752         CONF_VALUE *v;
753         
754         tmp=CONF_get_string(req_conf,SECTION,DISTINGUISHED_NAME);
755         if (tmp == NULL)
756                 {
757                 BIO_printf(bio_err,"unable to find '%s' in config\n",
758                         DISTINGUISHED_NAME);
759                 goto err;
760                 }
761         sk=CONF_get_section(req_conf,tmp);
762         if (sk == NULL)
763                 {
764                 BIO_printf(bio_err,"unable to get '%s' section\n",tmp);
765                 goto err;
766                 }
767
768         tmp_attr=CONF_get_string(req_conf,SECTION,ATTRIBUTES);
769         if (tmp_attr == NULL)
770                 attr=NULL;
771         else
772                 {
773                 attr=CONF_get_section(req_conf,tmp_attr);
774                 if (attr == NULL)
775                         {
776                         BIO_printf(bio_err,"unable to get '%s' section\n",tmp_attr);
777                         goto err;
778                         }
779                 }
780
781         ri=req->req_info;
782
783         BIO_printf(bio_err,"You are about to be asked to enter information that will be incorporated\n");
784         BIO_printf(bio_err,"into your certificate request.\n");
785         BIO_printf(bio_err,"What you are about to enter is what is called a Distinguished Name or a DN.\n");
786         BIO_printf(bio_err,"There are quite a few fields but you can leave some blank\n");
787         BIO_printf(bio_err,"For some fields there will be a default value,\n");
788         BIO_printf(bio_err,"If you enter '.', the field will be left blank.\n");
789         BIO_printf(bio_err,"-----\n");
790
791         /* setup version number */
792         if (!ASN1_INTEGER_set(ri->version,0L)) goto err; /* version 1 */
793
794         if (sk_num(sk))
795                 {
796                 i= -1;
797 start:          for (;;)
798                         {
799                         i++;
800                         if ((int)sk_num(sk) <= i) break;
801
802                         v=(CONF_VALUE *)sk_value(sk,i);
803                         p=NULL;
804                         type=v->name;
805                         for (j=0; type[j] != '\0'; j++)
806                                 {
807                                 if (    (type[j] == ':') ||
808                                         (type[j] == ',') ||
809                                         (type[j] == '.'))
810                                         p= (unsigned char *)&(type[j+1]);
811                                 }
812                         if (p != NULL)
813                                 type=(char *)p;
814                         if ((nid=OBJ_txt2nid(type)) == NID_undef)
815                                 goto start;
816
817                         sprintf(buf,"%s_default",v->name);
818                         if ((def=CONF_get_string(req_conf,tmp,buf)) == NULL)
819                                 def="";
820                                 
821                         sprintf(buf,"%s_value",v->name);
822                         if ((value=CONF_get_string(req_conf,tmp,buf)) == NULL)
823                                 value=NULL;
824
825                         sprintf(buf,"%s_min",v->name);
826                         min=(int)CONF_get_number(req_conf,tmp,buf);
827
828                         sprintf(buf,"%s_max",v->name);
829                         max=(int)CONF_get_number(req_conf,tmp,buf);
830
831                         if (!add_DN_object(ri->subject,v->value,def,value,nid,
832                                 min,max))
833                                 goto err;
834                         }
835                 if (sk_num(ri->subject->entries) == 0)
836                         {
837                         BIO_printf(bio_err,"error, no objects specified in config file\n");
838                         goto err;
839                         }
840
841                 if (attribs)
842                         {
843                         if ((attr != NULL) && (sk_num(attr) > 0))
844                                 {
845                                 BIO_printf(bio_err,"\nPlease enter the following 'extra' attributes\n");
846                                 BIO_printf(bio_err,"to be sent with your certificate request\n");
847                                 }
848
849                         i= -1;
850 start2:                 for (;;)
851                                 {
852                                 i++;
853                                 if ((attr == NULL) || ((int)sk_num(attr) <= i))
854                                         break;
855
856                                 v=(CONF_VALUE *)sk_value(attr,i);
857                                 type=v->name;
858                                 if ((nid=OBJ_txt2nid(type)) == NID_undef)
859                                         goto start2;
860
861                                 sprintf(buf,"%s_default",type);
862                                 if ((def=CONF_get_string(req_conf,tmp_attr,buf))
863                                         == NULL)
864                                         def="";
865                                 
866                                 sprintf(buf,"%s_value",type);
867                                 if ((value=CONF_get_string(req_conf,tmp_attr,buf))
868                                         == NULL)
869                                         value=NULL;
870
871                                 sprintf(buf,"%s_min",type);
872                                 min=(int)CONF_get_number(req_conf,tmp_attr,buf);
873
874                                 sprintf(buf,"%s_max",type);
875                                 max=(int)CONF_get_number(req_conf,tmp_attr,buf);
876
877                                 if (!add_attribute_object(ri->attributes,
878                                         v->value,def,value,nid,min,max))
879                                         goto err;
880                                 }
881                         }
882                 }
883         else
884                 {
885                 BIO_printf(bio_err,"No template, please set one up.\n");
886                 goto err;
887                 }
888
889         X509_REQ_set_pubkey(req,pkey);
890
891         ret=1;
892 err:
893         return(ret);
894         }
895
896 static int add_DN_object(n,text,def,value,nid,min,max)
897 X509_NAME *n;
898 char *text;
899 char *def;
900 char *value;
901 int nid;
902 int min;
903 int max;
904         {
905         int i,j,ret=0;
906         X509_NAME_ENTRY *ne=NULL;
907         MS_STATIC char buf[1024];
908
909         BIO_printf(bio_err,"%s [%s]:",text,def);
910         BIO_flush(bio_err);
911         if (value != NULL)
912                 {
913                 strcpy(buf,value);
914                 strcat(buf,"\n");
915                 BIO_printf(bio_err,"%s\n",value);
916                 }
917         else
918                 {
919                 buf[0]='\0';
920                 fgets(buf,1024,stdin);
921                 }
922
923         if (buf[0] == '\0') return(0);
924         else if (buf[0] == '\n')
925                 {
926                 if ((def == NULL) || (def[0] == '\0'))
927                         return(1);
928                 strcpy(buf,def);
929                 strcat(buf,"\n");
930                 }
931         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
932
933         i=strlen(buf);
934         if (buf[i-1] != '\n')
935                 {
936                 BIO_printf(bio_err,"weird input :-(\n");
937                 return(0);
938                 }
939         buf[--i]='\0';
940
941         j=ASN1_PRINTABLE_type((unsigned char *)buf,-1);
942         if (req_fix_data(nid,&j,i,min,max) == 0)
943                 goto err;
944         if ((ne=X509_NAME_ENTRY_create_by_NID(NULL,nid,j,(unsigned char *)buf,
945                 strlen(buf)))
946                 == NULL) goto err;
947         if (!X509_NAME_add_entry(n,ne,X509_NAME_entry_count(n),0))
948                 goto err;
949
950         ret=1;
951 err:
952         if (ne != NULL) X509_NAME_ENTRY_free(ne);
953         return(ret);
954         }
955
956 static int add_attribute_object(n,text,def,value,nid,min,max)
957 STACK *n;
958 char *text;
959 char *def;
960 char *value;
961 int nid;
962 int min;
963 int max;
964         {
965         int i,z;
966         X509_ATTRIBUTE *xa=NULL;
967         static char buf[1024];
968         ASN1_BIT_STRING *bs=NULL;
969         ASN1_TYPE *at=NULL;
970
971 start:
972         BIO_printf(bio_err,"%s [%s]:",text,def);
973         BIO_flush(bio_err);
974         if (value != NULL)
975                 {
976                 strcpy(buf,value);
977                 strcat(buf,"\n");
978                 BIO_printf(bio_err,"%s\n",value);
979                 }
980         else
981                 {
982                 buf[0]='\0';
983                 fgets(buf,1024,stdin);
984                 }
985
986         if (buf[0] == '\0') return(0);
987         else if (buf[0] == '\n')
988                 {
989                 if ((def == NULL) || (def[0] == '\0'))
990                         return(1);
991                 strcpy(buf,def);
992                 strcat(buf,"\n");
993                 }
994         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
995
996         i=strlen(buf);
997         if (buf[i-1] != '\n')
998                 {
999                 BIO_printf(bio_err,"weird input :-(\n");
1000                 return(0);
1001                 }
1002         buf[--i]='\0';
1003
1004         /* add object plus value */
1005         if ((xa=X509_ATTRIBUTE_new()) == NULL)
1006                 goto err;
1007         if ((xa->value.set=sk_new_null()) == NULL)
1008                 goto err;
1009         xa->set=1;
1010
1011         if (xa->object != NULL) ASN1_OBJECT_free(xa->object);
1012         xa->object=OBJ_nid2obj(nid);
1013
1014         if ((bs=ASN1_BIT_STRING_new()) == NULL) goto err;
1015
1016         bs->type=ASN1_PRINTABLE_type((unsigned char *)buf,-1);
1017
1018         z=req_fix_data(nid,&bs->type,i,min,max);
1019         if (z == 0)
1020                 {
1021                 if (value == NULL)
1022                         goto start;
1023                 else    goto err;
1024                 }
1025
1026         if (!ASN1_STRING_set(bs,(unsigned char *)buf,i+1))
1027                 { BIO_printf(bio_err,"Malloc failure\n"); goto err; }
1028
1029         if ((at=ASN1_TYPE_new()) == NULL)
1030                 { BIO_printf(bio_err,"Malloc failure\n"); goto err; }
1031
1032         ASN1_TYPE_set(at,bs->type,(char *)bs);
1033         sk_push(xa->value.set,(char *)at);
1034         bs=NULL;
1035         at=NULL;
1036         /* only one item per attribute */
1037
1038         if (!sk_push(n,(char *)xa)) goto err;
1039         return(1);
1040 err:
1041         if (xa != NULL) X509_ATTRIBUTE_free(xa);
1042         if (at != NULL) ASN1_TYPE_free(at);
1043         if (bs != NULL) ASN1_BIT_STRING_free(bs);
1044         return(0);
1045         }
1046
1047 static void MS_CALLBACK req_cb(p, n)
1048 int p;
1049 int n;
1050         {
1051         char c='*';
1052
1053         if (p == 0) c='.';
1054         if (p == 1) c='+';
1055         if (p == 2) c='*';
1056         if (p == 3) c='\n';
1057         BIO_write(bio_err,&c,1);
1058         BIO_flush(bio_err);
1059 #ifdef LINT
1060         p=n;
1061 #endif
1062         }
1063
1064 static int req_fix_data(nid,type,len,min,max)
1065 int nid;
1066 int *type;
1067 int len,min,max;
1068         {
1069         if (nid == NID_pkcs9_emailAddress)
1070                 *type=V_ASN1_IA5STRING;
1071         if ((nid == NID_commonName) && (*type == V_ASN1_IA5STRING))
1072                 *type=V_ASN1_T61STRING;
1073         if ((nid == NID_pkcs9_challengePassword) &&
1074                 (*type == V_ASN1_IA5STRING))
1075                 *type=V_ASN1_T61STRING;
1076
1077         if ((nid == NID_pkcs9_unstructuredName) &&
1078                 (*type == V_ASN1_T61STRING))
1079                 {
1080                 BIO_printf(bio_err,"invalid characters in string, please re-enter the string\n");
1081                 return(0);
1082                 }
1083         if (nid == NID_pkcs9_unstructuredName)
1084                 *type=V_ASN1_IA5STRING;
1085
1086         if (len < min)
1087                 {
1088                 BIO_printf(bio_err,"string is too short, it needs to be at least %d bytes long\n",min);
1089                 return(0);
1090                 }
1091         if ((max != 0) && (len > max))
1092                 {
1093                 BIO_printf(bio_err,"string is too long, it needs to be less than  %d bytes long\n",max);
1094                 return(0);
1095                 }
1096         return(1);
1097         }