a945610f92b938fbde87e69902798e7b8445b1a1
[openssl.git] / apps / req.c
1 /* apps/req.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 <stdio.h>
60 #include <stdlib.h>
61 #include <time.h>
62 #include <string.h>
63 #ifdef NO_STDIO
64 #define APPS_WIN16
65 #endif
66 #include "apps.h"
67 #include <openssl/bio.h>
68 #include <openssl/evp.h>
69 #include <openssl/conf.h>
70 #include <openssl/err.h>
71 #include <openssl/asn1.h>
72 #include <openssl/x509.h>
73 #include <openssl/x509v3.h>
74 #include <openssl/objects.h>
75 #include <openssl/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 #define V3_EXTENSIONS   "x509_extensions"
84 #define REQ_EXTENSIONS  "req_extensions"
85
86 #define DEFAULT_KEY_LENGTH      512
87 #define MIN_KEY_LENGTH          384
88
89 #undef PROG
90 #define PROG    req_main
91
92 /* -inform arg  - input format - default PEM (one of DER, TXT or PEM)
93  * -outform arg - output format - default PEM
94  * -in arg      - input file - default stdin
95  * -out arg     - output file - default stdout
96  * -verify      - check request signature
97  * -noout       - don't print stuff out.
98  * -text        - print out human readable text.
99  * -nodes       - no des encryption
100  * -config file - Load configuration file.
101  * -key file    - make a request using key in file (or use it for verification).
102  * -keyform     - key file format.
103  * -newkey      - make a key and a request.
104  * -modulus     - print RSA modulus.
105  * -x509        - output a self signed X509 structure instead.
106  * -asn1-kludge - output new certificate request in a format that some CA's
107  *                require.  This format is wrong
108  */
109
110 static int make_REQ(X509_REQ *req,EVP_PKEY *pkey,int attribs);
111 static int add_attribute_object(STACK_OF(X509_ATTRIBUTE) *n, char *text,
112                                 char *def, char *value, int nid, int min,
113                                 int max);
114 static int add_DN_object(X509_NAME *n, char *text, char *def, char *value,
115         int nid,int min,int max);
116 static void MS_CALLBACK req_cb(int p,int n,void *arg);
117 static int req_fix_data(int nid,int *type,int len,int min,int max);
118 static int check_end(char *str, char *end);
119 static int add_oid_section(LHASH *conf);
120 #ifndef MONOLITH
121 static char *default_config_file=NULL;
122 static LHASH *config=NULL;
123 #endif
124 static LHASH *req_conf=NULL;
125
126 #define TYPE_RSA        1
127 #define TYPE_DSA        2
128 #define TYPE_DH         3
129
130 int MAIN(int argc, char **argv)
131         {
132 #ifndef NO_DSA
133         DSA *dsa_params=NULL;
134 #endif
135         int ex=1,x509=0,days=30;
136         X509 *x509ss=NULL;
137         X509_REQ *req=NULL;
138         EVP_PKEY *pkey=NULL;
139         int i,badops=0,newreq=0,newkey= -1,pkey_type=0;
140         BIO *in=NULL,*out=NULL;
141         int informat,outformat,verify=0,noout=0,text=0,keyform=FORMAT_PEM;
142         int nodes=0,kludge=0;
143         char *infile,*outfile,*prog,*keyfile=NULL,*template=NULL,*keyout=NULL;
144         char *extensions = NULL;
145         char *req_exts = NULL;
146         EVP_CIPHER *cipher=NULL;
147         int modulus=0;
148         char *p;
149         const EVP_MD *md_alg=NULL,*digest=EVP_md5();
150 #ifndef MONOLITH
151         MS_STATIC char config_name[256];
152 #endif
153
154         req_conf = NULL;
155 #ifndef NO_DES
156         cipher=EVP_des_ede3_cbc();
157 #endif
158         apps_startup();
159
160         if (bio_err == NULL)
161                 if ((bio_err=BIO_new(BIO_s_file())) != NULL)
162                         BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);
163
164         infile=NULL;
165         outfile=NULL;
166         informat=FORMAT_PEM;
167         outformat=FORMAT_PEM;
168
169         prog=argv[0];
170         argc--;
171         argv++;
172         while (argc >= 1)
173                 {
174                 if      (strcmp(*argv,"-inform") == 0)
175                         {
176                         if (--argc < 1) goto bad;
177                         informat=str2fmt(*(++argv));
178                         }
179                 else if (strcmp(*argv,"-outform") == 0)
180                         {
181                         if (--argc < 1) goto bad;
182                         outformat=str2fmt(*(++argv));
183                         }
184                 else if (strcmp(*argv,"-key") == 0)
185                         {
186                         if (--argc < 1) goto bad;
187                         keyfile= *(++argv);
188                         }
189                 else if (strcmp(*argv,"-new") == 0)
190                         {
191                         pkey_type=TYPE_RSA;
192                         newreq=1;
193                         }
194                 else if (strcmp(*argv,"-config") == 0)
195                         {       
196                         if (--argc < 1) goto bad;
197                         template= *(++argv);
198                         }
199                 else if (strcmp(*argv,"-keyform") == 0)
200                         {
201                         if (--argc < 1) goto bad;
202                         keyform=str2fmt(*(++argv));
203                         }
204                 else if (strcmp(*argv,"-in") == 0)
205                         {
206                         if (--argc < 1) goto bad;
207                         infile= *(++argv);
208                         }
209                 else if (strcmp(*argv,"-out") == 0)
210                         {
211                         if (--argc < 1) goto bad;
212                         outfile= *(++argv);
213                         }
214                 else if (strcmp(*argv,"-keyout") == 0)
215                         {
216                         if (--argc < 1) goto bad;
217                         keyout= *(++argv);
218                         }
219                 else if (strcmp(*argv,"-newkey") == 0)
220                         {
221                         int is_numeric;
222
223                         if (--argc < 1) goto bad;
224                         p= *(++argv);
225                         is_numeric = p[0] >= '0' && p[0] <= '9';
226                         if (strncmp("rsa:",p,4) == 0 || is_numeric)
227                                 {
228                                 pkey_type=TYPE_RSA;
229                                 if(!is_numeric)
230                                     p+=4;
231                                 newkey= atoi(p);
232                                 }
233                         else
234 #ifndef NO_DSA
235                                 if (strncmp("dsa:",p,4) == 0)
236                                 {
237                                 X509 *xtmp=NULL;
238                                 EVP_PKEY *dtmp;
239
240                                 pkey_type=TYPE_DSA;
241                                 p+=4;
242                                 if ((in=BIO_new_file(p,"r")) == NULL)
243                                         {
244                                         perror(p);
245                                         goto end;
246                                         }
247                                 if ((dsa_params=PEM_read_bio_DSAparams(in,NULL,NULL,NULL)) == NULL)
248                                         {
249                                         ERR_clear_error();
250                                         (void)BIO_reset(in);
251                                         if ((xtmp=PEM_read_bio_X509(in,NULL,NULL,NULL)) == NULL)
252                                                 {
253                                                 BIO_printf(bio_err,"unable to load DSA parameters from file\n");
254                                                 goto end;
255                                                 }
256
257                                         dtmp=X509_get_pubkey(xtmp);
258                                         if (dtmp->type == EVP_PKEY_DSA)
259                                                 dsa_params=DSAparams_dup(dtmp->pkey.dsa);
260                                         EVP_PKEY_free(dtmp);
261                                         X509_free(xtmp);
262                                         if (dsa_params == NULL)
263                                                 {
264                                                 BIO_printf(bio_err,"Certificate does not contain DSA parameters\n");
265                                                 goto end;
266                                                 }
267                                         }
268                                 BIO_free(in);
269                                 newkey=BN_num_bits(dsa_params->p);
270                                 in=NULL;
271                                 }
272                         else 
273 #endif
274 #ifndef NO_DH
275                                 if (strncmp("dh:",p,4) == 0)
276                                 {
277                                 pkey_type=TYPE_DH;
278                                 p+=3;
279                                 }
280                         else
281 #endif
282                                 pkey_type=TYPE_RSA;
283
284                         newreq=1;
285                         }
286                 else if (strcmp(*argv,"-modulus") == 0)
287                         modulus=1;
288                 else if (strcmp(*argv,"-verify") == 0)
289                         verify=1;
290                 else if (strcmp(*argv,"-nodes") == 0)
291                         nodes=1;
292                 else if (strcmp(*argv,"-noout") == 0)
293                         noout=1;
294                 else if (strcmp(*argv,"-text") == 0)
295                         text=1;
296                 else if (strcmp(*argv,"-x509") == 0)
297                         x509=1;
298                 else if (strcmp(*argv,"-asn1-kludge") == 0)
299                         kludge=1;
300                 else if (strcmp(*argv,"-no-asn1-kludge") == 0)
301                         kludge=0;
302                 else if (strcmp(*argv,"-days") == 0)
303                         {
304                         if (--argc < 1) goto bad;
305                         days= atoi(*(++argv));
306                         if (days == 0) days=30;
307                         }
308                 else if ((md_alg=EVP_get_digestbyname(&((*argv)[1]))) != NULL)
309                         {
310                         /* ok */
311                         digest=md_alg;
312                         }
313                 else if (strcmp(*argv,"-extensions") == 0)
314                         {
315                         if (--argc < 1) goto bad;
316                         extensions = *(++argv);
317                         }
318                 else if (strcmp(*argv,"-reqexts") == 0)
319                         {
320                         if (--argc < 1) goto bad;
321                         req_exts = *(++argv);
322                         }
323                 else
324                         {
325                         BIO_printf(bio_err,"unknown option %s\n",*argv);
326                         badops=1;
327                         break;
328                         }
329                 argc--;
330                 argv++;
331                 }
332
333         if (badops)
334                 {
335 bad:
336                 BIO_printf(bio_err,"%s [options] <infile >outfile\n",prog);
337                 BIO_printf(bio_err,"where options  are\n");
338                 BIO_printf(bio_err," -inform arg    input format - one of DER TXT PEM\n");
339                 BIO_printf(bio_err," -outform arg   output format - one of DER TXT PEM\n");
340                 BIO_printf(bio_err," -in arg        input file\n");
341                 BIO_printf(bio_err," -out arg       output file\n");
342                 BIO_printf(bio_err," -text          text form of request\n");
343                 BIO_printf(bio_err," -noout         do not output REQ\n");
344                 BIO_printf(bio_err," -verify        verify signature on REQ\n");
345                 BIO_printf(bio_err," -modulus       RSA modulus\n");
346                 BIO_printf(bio_err," -nodes         don't encrypt the output key\n");
347                 BIO_printf(bio_err," -key file  use the private key contained in file\n");
348                 BIO_printf(bio_err," -keyform arg   key file format\n");
349                 BIO_printf(bio_err," -keyout arg    file to send the key to\n");
350                 BIO_printf(bio_err," -newkey rsa:bits generate a new RSA key of 'bits' in size\n");
351                 BIO_printf(bio_err," -newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'\n");
352
353                 BIO_printf(bio_err," -[digest]      Digest to sign with (md5, sha1, md2, mdc2)\n");
354                 BIO_printf(bio_err," -config file   request template file.\n");
355                 BIO_printf(bio_err," -new           new request.\n");
356                 BIO_printf(bio_err," -x509          output a x509 structure instead of a cert. req.\n");
357                 BIO_printf(bio_err," -days          number of days a x509 generated by -x509 is valid for.\n");
358                 BIO_printf(bio_err," -asn1-kludge   Output the 'request' in a format that is wrong but some CA's\n");
359                 BIO_printf(bio_err,"                have been reported as requiring\n");
360                 BIO_printf(bio_err,"                [ It is now always turned on but can be turned off with -no-asn1-kludge ]\n");
361                 BIO_printf(bio_err," -extensions .. specify certificate extension section (override value in config file)\n");
362                 BIO_printf(bio_err," -reqexts ..    specify request extension section (override value in config file)\n");
363                 goto end;
364                 }
365
366         ERR_load_crypto_strings();
367         X509V3_add_standard_extensions();
368
369 #ifndef MONOLITH
370         /* Lets load up our environment a little */
371         p=getenv("OPENSSL_CONF");
372         if (p == NULL)
373                 p=getenv("SSLEAY_CONF");
374         if (p == NULL)
375                 {
376                 strcpy(config_name,X509_get_default_cert_area());
377 #ifndef VMS
378                 strcat(config_name,"/");
379 #endif
380                 strcat(config_name,OPENSSL_CONF);
381                 p=config_name;
382                 }
383         default_config_file=p;
384         config=CONF_load(config,p,NULL);
385 #endif
386
387         if (template != NULL)
388                 {
389                 long errline;
390
391                 BIO_printf(bio_err,"Using configuration from %s\n",template);
392                 req_conf=CONF_load(NULL,template,&errline);
393                 if (req_conf == NULL)
394                         {
395                         BIO_printf(bio_err,"error on line %ld of %s\n",errline,template);
396                         goto end;
397                         }
398                 }
399         else
400                 {
401                 req_conf=config;
402                 BIO_printf(bio_err,"Using configuration from %s\n",
403                         default_config_file);
404                 if (req_conf == NULL)
405                         {
406                         BIO_printf(bio_err,"Unable to load config info\n");
407                         }
408                 }
409
410         if (req_conf != NULL)
411                 {
412                 p=CONF_get_string(req_conf,NULL,"oid_file");
413                 if (p != NULL)
414                         {
415                         BIO *oid_bio;
416
417                         oid_bio=BIO_new_file(p,"r");
418                         if (oid_bio == NULL) 
419                                 {
420                                 /*
421                                 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
422                                 ERR_print_errors(bio_err);
423                                 */
424                                 }
425                         else
426                                 {
427                                 OBJ_create_objects(oid_bio);
428                                 BIO_free(oid_bio);
429                                 }
430                         }
431                 }
432                 if(!add_oid_section(req_conf)) goto end;
433
434         if ((md_alg == NULL) &&
435                 ((p=CONF_get_string(req_conf,SECTION,"default_md")) != NULL))
436                 {
437                 if ((md_alg=EVP_get_digestbyname(p)) != NULL)
438                         digest=md_alg;
439                 }
440
441         if(!extensions)
442                 extensions = CONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
443         if(extensions) {
444                 /* Check syntax of file */
445                 X509V3_CTX ctx;
446                 X509V3_set_ctx_test(&ctx);
447                 X509V3_set_conf_lhash(&ctx, req_conf);
448                 if(!X509V3_EXT_add_conf(req_conf, &ctx, extensions, NULL)) {
449                         BIO_printf(bio_err,
450                          "Error Loading extension section %s\n", extensions);
451                         goto end;
452                 }
453         }
454
455         if(!req_exts)
456                 req_exts = CONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
457         if(req_exts) {
458                 /* Check syntax of file */
459                 X509V3_CTX ctx;
460                 X509V3_set_ctx_test(&ctx);
461                 X509V3_set_conf_lhash(&ctx, req_conf);
462                 if(!X509V3_EXT_add_conf(req_conf, &ctx, req_exts, NULL)) {
463                         BIO_printf(bio_err,
464                          "Error Loading request extension section %s\n",
465                                                                 req_exts);
466                         goto end;
467                 }
468         }
469
470         in=BIO_new(BIO_s_file());
471         out=BIO_new(BIO_s_file());
472         if ((in == NULL) || (out == NULL))
473                 goto end;
474
475         if (keyfile != NULL)
476                 {
477                 if (BIO_read_filename(in,keyfile) <= 0)
478                         {
479                         perror(keyfile);
480                         goto end;
481                         }
482
483 /*              if (keyform == FORMAT_ASN1)
484                         rsa=d2i_RSAPrivateKey_bio(in,NULL);
485                 else */
486                 if (keyform == FORMAT_PEM)
487                         pkey=PEM_read_bio_PrivateKey(in,NULL,NULL,NULL);
488                 else
489                         {
490                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
491                         goto end;
492                         }
493
494                 if (pkey == NULL)
495                         {
496                         BIO_printf(bio_err,"unable to load Private key\n");
497                         goto end;
498                         }
499                 }
500
501         if (newreq && (pkey == NULL))
502                 {
503                 char *randfile = CONF_get_string(req_conf,SECTION,"RANDFILE");
504                 app_RAND_load_file(randfile, bio_err, 0);
505         
506                 if (newkey <= 0)
507                         {
508                         newkey=(int)CONF_get_number(req_conf,SECTION,BITS);
509                         if (newkey <= 0)
510                                 newkey=DEFAULT_KEY_LENGTH;
511                         }
512
513                 if (newkey < MIN_KEY_LENGTH)
514                         {
515                         BIO_printf(bio_err,"private key length is too short,\n");
516                         BIO_printf(bio_err,"it needs to be at least %d bits, not %d\n",MIN_KEY_LENGTH,newkey);
517                         goto end;
518                         }
519                 BIO_printf(bio_err,"Generating a %d bit %s private key\n",
520                         newkey,(pkey_type == TYPE_RSA)?"RSA":"DSA");
521
522                 if ((pkey=EVP_PKEY_new()) == NULL) goto end;
523
524 #ifndef NO_RSA
525                 if (pkey_type == TYPE_RSA)
526                         {
527                         if (!EVP_PKEY_assign_RSA(pkey,
528                                 RSA_generate_key(newkey,0x10001,
529                                         req_cb,bio_err)))
530                                 goto end;
531                         }
532                 else
533 #endif
534 #ifndef NO_DSA
535                         if (pkey_type == TYPE_DSA)
536                         {
537                         if (!DSA_generate_key(dsa_params)) goto end;
538                         if (!EVP_PKEY_assign_DSA(pkey,dsa_params)) goto end;
539                         dsa_params=NULL;
540                         }
541 #endif
542
543                 app_RAND_write_file(randfile, bio_err);
544
545                 if (pkey == NULL) goto end;
546
547                 if (keyout == NULL)
548                         keyout=CONF_get_string(req_conf,SECTION,KEYFILE);
549
550                 if (keyout == NULL)
551                         {
552                         BIO_printf(bio_err,"writing new private key to stdout\n");
553                         BIO_set_fp(out,stdout,BIO_NOCLOSE);
554                         }
555                 else
556                         {
557                         BIO_printf(bio_err,"writing new private key to '%s'\n",keyout);
558                         if (BIO_write_filename(out,keyout) <= 0)
559                                 {
560                                 perror(keyout);
561                                 goto end;
562                                 }
563                         }
564
565                 p=CONF_get_string(req_conf,SECTION,"encrypt_rsa_key");
566                 if (p == NULL)
567                         p=CONF_get_string(req_conf,SECTION,"encrypt_key");
568                 if ((p != NULL) && (strcmp(p,"no") == 0))
569                         cipher=NULL;
570                 if (nodes) cipher=NULL;
571                 
572                 i=0;
573 loop:
574                 if (!PEM_write_bio_PrivateKey(out,pkey,cipher,
575                         NULL,0,NULL,NULL))
576                         {
577                         if ((ERR_GET_REASON(ERR_peek_error()) ==
578                                 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3))
579                                 {
580                                 ERR_clear_error();
581                                 i++;
582                                 goto loop;
583                                 }
584                         goto end;
585                         }
586                 BIO_printf(bio_err,"-----\n");
587                 }
588
589         if (!newreq)
590                 {
591                 /* Since we are using a pre-existing certificate
592                  * request, the kludge 'format' info should not be
593                  * changed. */
594                 kludge= -1;
595                 if (infile == NULL)
596                         BIO_set_fp(in,stdin,BIO_NOCLOSE);
597                 else
598                         {
599                         if (BIO_read_filename(in,infile) <= 0)
600                                 {
601                                 perror(infile);
602                                 goto end;
603                                 }
604                         }
605
606                 if      (informat == FORMAT_ASN1)
607                         req=d2i_X509_REQ_bio(in,NULL);
608                 else if (informat == FORMAT_PEM)
609                         req=PEM_read_bio_X509_REQ(in,NULL,NULL,NULL);
610                 else
611                         {
612                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
613                         goto end;
614                         }
615                 if (req == NULL)
616                         {
617                         BIO_printf(bio_err,"unable to load X509 request\n");
618                         goto end;
619                         }
620                 }
621
622         if (newreq || x509)
623                 {
624 #ifndef NO_DSA
625                 if (pkey->type == EVP_PKEY_DSA)
626                         digest=EVP_dss1();
627 #endif
628
629                 if (pkey == NULL)
630                         {
631                         BIO_printf(bio_err,"you need to specify a private key\n");
632                         goto end;
633                         }
634                 if (req == NULL)
635                         {
636                         req=X509_REQ_new();
637                         if (req == NULL)
638                                 {
639                                 goto end;
640                                 }
641
642                         i=make_REQ(req,pkey,!x509);
643                         if (kludge >= 0)
644                                 req->req_info->req_kludge=kludge;
645                         if (!i)
646                                 {
647                                 BIO_printf(bio_err,"problems making Certificate Request\n");
648                                 goto end;
649                                 }
650                         }
651                 if (x509)
652                         {
653                         EVP_PKEY *tmppkey;
654                         X509V3_CTX ext_ctx;
655                         if ((x509ss=X509_new()) == NULL) goto end;
656
657                         /* Set version to V3 */
658                         if(!X509_set_version(x509ss, 2)) goto end;
659                         ASN1_INTEGER_set(X509_get_serialNumber(x509ss),0L);
660
661                         X509_set_issuer_name(x509ss,
662                                 X509_REQ_get_subject_name(req));
663                         X509_gmtime_adj(X509_get_notBefore(x509ss),0);
664                         X509_gmtime_adj(X509_get_notAfter(x509ss),
665                                 (long)60*60*24*days);
666                         X509_set_subject_name(x509ss,
667                                 X509_REQ_get_subject_name(req));
668                         tmppkey = X509_REQ_get_pubkey(req);
669                         X509_set_pubkey(x509ss,tmppkey);
670                         EVP_PKEY_free(tmppkey);
671
672                         /* Set up V3 context struct */
673
674                         X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
675                         X509V3_set_conf_lhash(&ext_ctx, req_conf);
676
677                         /* Add extensions */
678                         if(extensions && !X509V3_EXT_add_conf(req_conf, 
679                                         &ext_ctx, extensions, x509ss))
680                             {
681                             BIO_printf(bio_err,
682                                        "Error Loading extension section %s\n",
683                                        extensions);
684                             goto end;
685                             }
686
687                         if (!(i=X509_sign(x509ss,pkey,digest)))
688                                 goto end;
689                         }
690                 else
691                         {
692                         X509V3_CTX ext_ctx;
693
694                         /* Set up V3 context struct */
695
696                         X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
697                         X509V3_set_conf_lhash(&ext_ctx, req_conf);
698
699                         /* Add extensions */
700                         if(req_exts && !X509V3_EXT_REQ_add_conf(req_conf, 
701                                         &ext_ctx, req_exts, req))
702                             {
703                             BIO_printf(bio_err,
704                                        "Error Loading extension section %s\n",
705                                        req_exts);
706                             goto end;
707                             }
708                         if (!(i=X509_REQ_sign(req,pkey,digest)))
709                                 goto end;
710                         }
711                 }
712
713         if (verify && !x509)
714                 {
715                 int tmp=0;
716
717                 if (pkey == NULL)
718                         {
719                         pkey=X509_REQ_get_pubkey(req);
720                         tmp=1;
721                         if (pkey == NULL) goto end;
722                         }
723
724                 i=X509_REQ_verify(req,pkey);
725                 if (tmp) {
726                         EVP_PKEY_free(pkey);
727                         pkey=NULL;
728                 }
729
730                 if (i < 0)
731                         {
732                         goto end;
733                         }
734                 else if (i == 0)
735                         {
736                         BIO_printf(bio_err,"verify failure\n");
737                         }
738                 else /* if (i > 0) */
739                         BIO_printf(bio_err,"verify OK\n");
740                 }
741
742         if (noout && !text && !modulus)
743                 {
744                 ex=0;
745                 goto end;
746                 }
747
748         if (outfile == NULL)
749                 BIO_set_fp(out,stdout,BIO_NOCLOSE);
750         else
751                 {
752                 if ((keyout != NULL) && (strcmp(outfile,keyout) == 0))
753                         i=(int)BIO_append_filename(out,outfile);
754                 else
755                         i=(int)BIO_write_filename(out,outfile);
756                 if (!i)
757                         {
758                         perror(outfile);
759                         goto end;
760                         }
761                 }
762
763         if (text)
764                 {
765                 if (x509)
766                         X509_print(out,x509ss);
767                 else    
768                         X509_REQ_print(out,req);
769                 }
770
771         if (modulus)
772                 {
773                 EVP_PKEY *pubkey;
774
775                 if (x509)
776                         pubkey=X509_get_pubkey(x509ss);
777                 else
778                         pubkey=X509_REQ_get_pubkey(req);
779                 if (pubkey == NULL)
780                         {
781                         fprintf(stdout,"Modulus=unavailable\n");
782                         goto end; 
783                         }
784                 fprintf(stdout,"Modulus=");
785 #ifndef NO_RSA
786                 if (pubkey->type == EVP_PKEY_RSA)
787                         BN_print(out,pubkey->pkey.rsa->n);
788                 else
789 #endif
790                         fprintf(stdout,"Wrong Algorithm type");
791                 fprintf(stdout,"\n");
792                 }
793
794         if (!noout && !x509)
795                 {
796                 if      (outformat == FORMAT_ASN1)
797                         i=i2d_X509_REQ_bio(out,req);
798                 else if (outformat == FORMAT_PEM)
799                         i=PEM_write_bio_X509_REQ(out,req);
800                 else    {
801                         BIO_printf(bio_err,"bad output format specified for outfile\n");
802                         goto end;
803                         }
804                 if (!i)
805                         {
806                         BIO_printf(bio_err,"unable to write X509 request\n");
807                         goto end;
808                         }
809                 }
810         if (!noout && x509 && (x509ss != NULL))
811                 {
812                 if      (outformat == FORMAT_ASN1)
813                         i=i2d_X509_bio(out,x509ss);
814                 else if (outformat == FORMAT_PEM)
815                         i=PEM_write_bio_X509(out,x509ss);
816                 else    {
817                         BIO_printf(bio_err,"bad output format specified for outfile\n");
818                         goto end;
819                         }
820                 if (!i)
821                         {
822                         BIO_printf(bio_err,"unable to write X509 certificate\n");
823                         goto end;
824                         }
825                 }
826         ex=0;
827 end:
828         if (ex)
829                 {
830                 ERR_print_errors(bio_err);
831                 }
832         if ((req_conf != NULL) && (req_conf != config)) CONF_free(req_conf);
833         BIO_free(in);
834         BIO_free(out);
835         EVP_PKEY_free(pkey);
836         X509_REQ_free(req);
837         X509_free(x509ss);
838         X509V3_EXT_cleanup();
839         OBJ_cleanup();
840 #ifndef NO_DSA
841         if (dsa_params != NULL) DSA_free(dsa_params);
842 #endif
843         EXIT(ex);
844         }
845
846 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, int attribs)
847         {
848         int ret=0,i;
849         char *p,*q;
850         X509_REQ_INFO *ri;
851         char buf[100];
852         int nid,min,max;
853         char *type,*def,*tmp,*value,*tmp_attr;
854         STACK_OF(CONF_VALUE) *sk, *attr=NULL;
855         CONF_VALUE *v;
856         
857         tmp=CONF_get_string(req_conf,SECTION,DISTINGUISHED_NAME);
858         if (tmp == NULL)
859                 {
860                 BIO_printf(bio_err,"unable to find '%s' in config\n",
861                         DISTINGUISHED_NAME);
862                 goto err;
863                 }
864         sk=CONF_get_section(req_conf,tmp);
865         if (sk == NULL)
866                 {
867                 BIO_printf(bio_err,"unable to get '%s' section\n",tmp);
868                 goto err;
869                 }
870
871         tmp_attr=CONF_get_string(req_conf,SECTION,ATTRIBUTES);
872         if (tmp_attr == NULL)
873                 attr=NULL;
874         else
875                 {
876                 attr=CONF_get_section(req_conf,tmp_attr);
877                 if (attr == NULL)
878                         {
879                         BIO_printf(bio_err,"unable to get '%s' section\n",tmp_attr);
880                         goto err;
881                         }
882                 }
883
884         ri=req->req_info;
885
886         BIO_printf(bio_err,"You are about to be asked to enter information that will be incorporated\n");
887         BIO_printf(bio_err,"into your certificate request.\n");
888         BIO_printf(bio_err,"What you are about to enter is what is called a Distinguished Name or a DN.\n");
889         BIO_printf(bio_err,"There are quite a few fields but you can leave some blank\n");
890         BIO_printf(bio_err,"For some fields there will be a default value,\n");
891         BIO_printf(bio_err,"If you enter '.', the field will be left blank.\n");
892         BIO_printf(bio_err,"-----\n");
893
894         /* setup version number */
895         if (!ASN1_INTEGER_set(ri->version,0L)) goto err; /* version 1 */
896
897         if (sk_CONF_VALUE_num(sk))
898                 {
899                 i= -1;
900 start:          for (;;)
901                         {
902                         i++;
903                         if (sk_CONF_VALUE_num(sk) <= i) break;
904
905                         v=sk_CONF_VALUE_value(sk,i);
906                         p=q=NULL;
907                         type=v->name;
908                         if(!check_end(type,"_min") || !check_end(type,"_max") ||
909                                 !check_end(type,"_default") ||
910                                          !check_end(type,"_value")) continue;
911                         /* Skip past any leading X. X: X, etc to allow for
912                          * multiple instances 
913                          */
914                         for(p = v->name; *p ; p++) 
915                                 if ((*p == ':') || (*p == ',') ||
916                                                          (*p == '.')) {
917                                         p++;
918                                         if(*p) type = p;
919                                         break;
920                                 }
921                         /* If OBJ not recognised ignore it */
922                         if ((nid=OBJ_txt2nid(type)) == NID_undef) goto start;
923                         sprintf(buf,"%s_default",v->name);
924                         if ((def=CONF_get_string(req_conf,tmp,buf)) == NULL)
925                                 def="";
926                                 
927                         sprintf(buf,"%s_value",v->name);
928                         if ((value=CONF_get_string(req_conf,tmp,buf)) == NULL)
929                                 value=NULL;
930
931                         sprintf(buf,"%s_min",v->name);
932                         min=(int)CONF_get_number(req_conf,tmp,buf);
933
934                         sprintf(buf,"%s_max",v->name);
935                         max=(int)CONF_get_number(req_conf,tmp,buf);
936
937                         if (!add_DN_object(ri->subject,v->value,def,value,nid,
938                                 min,max))
939                                 goto err;
940                         }
941                 if (sk_X509_NAME_ENTRY_num(ri->subject->entries) == 0)
942                         {
943                         BIO_printf(bio_err,"error, no objects specified in config file\n");
944                         goto err;
945                         }
946
947                 if (attribs)
948                         {
949                         if ((attr != NULL) && (sk_CONF_VALUE_num(attr) > 0))
950                                 {
951                                 BIO_printf(bio_err,"\nPlease enter the following 'extra' attributes\n");
952                                 BIO_printf(bio_err,"to be sent with your certificate request\n");
953                                 }
954
955                         i= -1;
956 start2:                 for (;;)
957                                 {
958                                 i++;
959                                 if ((attr == NULL) ||
960                                             (sk_CONF_VALUE_num(attr) <= i))
961                                         break;
962
963                                 v=sk_CONF_VALUE_value(attr,i);
964                                 type=v->name;
965                                 if ((nid=OBJ_txt2nid(type)) == NID_undef)
966                                         goto start2;
967
968                                 sprintf(buf,"%s_default",type);
969                                 if ((def=CONF_get_string(req_conf,tmp_attr,buf))
970                                         == NULL)
971                                         def="";
972                                 
973                                 sprintf(buf,"%s_value",type);
974                                 if ((value=CONF_get_string(req_conf,tmp_attr,buf))
975                                         == NULL)
976                                         value=NULL;
977
978                                 sprintf(buf,"%s_min",type);
979                                 min=(int)CONF_get_number(req_conf,tmp_attr,buf);
980
981                                 sprintf(buf,"%s_max",type);
982                                 max=(int)CONF_get_number(req_conf,tmp_attr,buf);
983
984                                 if (!add_attribute_object(ri->attributes,
985                                         v->value,def,value,nid,min,max))
986                                         goto err;
987                                 }
988                         }
989                 }
990         else
991                 {
992                 BIO_printf(bio_err,"No template, please set one up.\n");
993                 goto err;
994                 }
995
996         X509_REQ_set_pubkey(req,pkey);
997
998         ret=1;
999 err:
1000         return(ret);
1001         }
1002
1003 static int add_DN_object(X509_NAME *n, char *text, char *def, char *value,
1004              int nid, int min, int max)
1005         {
1006         int i,j,ret=0;
1007         X509_NAME_ENTRY *ne=NULL;
1008         MS_STATIC char buf[1024];
1009
1010         BIO_printf(bio_err,"%s [%s]:",text,def);
1011         (void)BIO_flush(bio_err);
1012         if (value != NULL)
1013                 {
1014                 strcpy(buf,value);
1015                 strcat(buf,"\n");
1016                 BIO_printf(bio_err,"%s\n",value);
1017                 }
1018         else
1019                 {
1020                 buf[0]='\0';
1021                 fgets(buf,1024,stdin);
1022                 }
1023
1024         if (buf[0] == '\0') return(0);
1025         else if (buf[0] == '\n')
1026                 {
1027                 if ((def == NULL) || (def[0] == '\0'))
1028                         return(1);
1029                 strcpy(buf,def);
1030                 strcat(buf,"\n");
1031                 }
1032         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1033
1034         i=strlen(buf);
1035         if (buf[i-1] != '\n')
1036                 {
1037                 BIO_printf(bio_err,"weird input :-(\n");
1038                 return(0);
1039                 }
1040         buf[--i]='\0';
1041
1042         j=ASN1_PRINTABLE_type((unsigned char *)buf,-1);
1043         if (req_fix_data(nid,&j,i,min,max) == 0)
1044                 goto err;
1045 #ifdef CHARSET_EBCDIC
1046         ebcdic2ascii(buf, buf, i);
1047 #endif
1048         if ((ne=X509_NAME_ENTRY_create_by_NID(NULL,nid,j,(unsigned char *)buf,
1049                 strlen(buf)))
1050                 == NULL) goto err;
1051         if (!X509_NAME_add_entry(n,ne,X509_NAME_entry_count(n),0))
1052                 goto err;
1053
1054         ret=1;
1055 err:
1056         if (ne != NULL) X509_NAME_ENTRY_free(ne);
1057         return(ret);
1058         }
1059
1060 static int add_attribute_object(STACK_OF(X509_ATTRIBUTE) *n, char *text,
1061                                 char *def, char *value, int nid, int min,
1062                                 int max)
1063         {
1064         int i,z;
1065         X509_ATTRIBUTE *xa=NULL;
1066         static char buf[1024];
1067         ASN1_BIT_STRING *bs=NULL;
1068         ASN1_TYPE *at=NULL;
1069
1070 start:
1071         BIO_printf(bio_err,"%s [%s]:",text,def);
1072         (void)BIO_flush(bio_err);
1073         if (value != NULL)
1074                 {
1075                 strcpy(buf,value);
1076                 strcat(buf,"\n");
1077                 BIO_printf(bio_err,"%s\n",value);
1078                 }
1079         else
1080                 {
1081                 buf[0]='\0';
1082                 fgets(buf,1024,stdin);
1083                 }
1084
1085         if (buf[0] == '\0') return(0);
1086         else if (buf[0] == '\n')
1087                 {
1088                 if ((def == NULL) || (def[0] == '\0'))
1089                         return(1);
1090                 strcpy(buf,def);
1091                 strcat(buf,"\n");
1092                 }
1093         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1094
1095         i=strlen(buf);
1096         if (buf[i-1] != '\n')
1097                 {
1098                 BIO_printf(bio_err,"weird input :-(\n");
1099                 return(0);
1100                 }
1101         buf[--i]='\0';
1102
1103         /* add object plus value */
1104         if ((xa=X509_ATTRIBUTE_new()) == NULL)
1105                 goto err;
1106         if ((xa->value.set=sk_ASN1_TYPE_new_null()) == NULL)
1107                 goto err;
1108         xa->set=1;
1109
1110         if (xa->object != NULL) ASN1_OBJECT_free(xa->object);
1111         xa->object=OBJ_nid2obj(nid);
1112
1113         if ((bs=ASN1_BIT_STRING_new()) == NULL) goto err;
1114
1115         bs->type=ASN1_PRINTABLE_type((unsigned char *)buf,-1);
1116
1117         z=req_fix_data(nid,&bs->type,i,min,max);
1118         if (z == 0)
1119                 {
1120                 if (value == NULL)
1121                         goto start;
1122                 else    goto err;
1123                 }
1124
1125         if (!ASN1_STRING_set(bs,(unsigned char *)buf,i+1))
1126                 { BIO_printf(bio_err,"Malloc failure\n"); goto err; }
1127
1128         if ((at=ASN1_TYPE_new()) == NULL)
1129                 { BIO_printf(bio_err,"Malloc failure\n"); goto err; }
1130
1131         ASN1_TYPE_set(at,bs->type,(char *)bs);
1132         sk_ASN1_TYPE_push(xa->value.set,at);
1133         bs=NULL;
1134         at=NULL;
1135         /* only one item per attribute */
1136
1137         if (!sk_X509_ATTRIBUTE_push(n,xa)) goto err;
1138         return(1);
1139 err:
1140         if (xa != NULL) X509_ATTRIBUTE_free(xa);
1141         if (at != NULL) ASN1_TYPE_free(at);
1142         if (bs != NULL) ASN1_BIT_STRING_free(bs);
1143         return(0);
1144         }
1145
1146 static void MS_CALLBACK req_cb(int p, int n, void *arg)
1147         {
1148         char c='*';
1149
1150         if (p == 0) c='.';
1151         if (p == 1) c='+';
1152         if (p == 2) c='*';
1153         if (p == 3) c='\n';
1154         BIO_write((BIO *)arg,&c,1);
1155         (void)BIO_flush((BIO *)arg);
1156 #ifdef LINT
1157         p=n;
1158 #endif
1159         }
1160
1161 static int req_fix_data(int nid, int *type, int len, int min, int max)
1162         {
1163         if (nid == NID_pkcs9_emailAddress)
1164                 *type=V_ASN1_IA5STRING;
1165         if ((nid == NID_commonName) && (*type == V_ASN1_IA5STRING))
1166                 *type=V_ASN1_T61STRING;
1167         if ((nid == NID_pkcs9_challengePassword) &&
1168                 (*type == V_ASN1_IA5STRING))
1169                 *type=V_ASN1_T61STRING;
1170
1171         if ((nid == NID_pkcs9_unstructuredName) &&
1172                 (*type == V_ASN1_T61STRING))
1173                 {
1174                 BIO_printf(bio_err,"invalid characters in string, please re-enter the string\n");
1175                 return(0);
1176                 }
1177         if (nid == NID_pkcs9_unstructuredName)
1178                 *type=V_ASN1_IA5STRING;
1179
1180         if (len < min)
1181                 {
1182                 BIO_printf(bio_err,"string is too short, it needs to be at least %d bytes long\n",min);
1183                 return(0);
1184                 }
1185         if ((max != 0) && (len > max))
1186                 {
1187                 BIO_printf(bio_err,"string is too long, it needs to be less than  %d bytes long\n",max);
1188                 return(0);
1189                 }
1190         return(1);
1191         }
1192
1193 /* Check if the end of a string matches 'end' */
1194 static int check_end(char *str, char *end)
1195 {
1196         int elen, slen; 
1197         char *tmp;
1198         elen = strlen(end);
1199         slen = strlen(str);
1200         if(elen > slen) return 1;
1201         tmp = str + slen - elen;
1202         return strcmp(tmp, end);
1203 }
1204
1205 static int add_oid_section(LHASH *conf)
1206 {       
1207         char *p;
1208         STACK_OF(CONF_VALUE) *sktmp;
1209         CONF_VALUE *cnf;
1210         int i;
1211         if(!(p=CONF_get_string(conf,NULL,"oid_section"))) return 1;
1212         if(!(sktmp = CONF_get_section(conf, p))) {
1213                 BIO_printf(bio_err, "problem loading oid section %s\n", p);
1214                 return 0;
1215         }
1216         for(i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
1217                 cnf = sk_CONF_VALUE_value(sktmp, i);
1218                 if(OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
1219                         BIO_printf(bio_err, "problem creating object %s=%s\n",
1220                                                          cnf->name, cnf->value);
1221                         return 0;
1222                 }
1223         }
1224         return 1;
1225 }