Allow the extension section specified in config files to be overridden
[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/rand.h>
70 #include <openssl/conf.h>
71 #include <openssl/err.h>
72 #include <openssl/asn1.h>
73 #include <openssl/x509.h>
74 #include <openssl/x509v3.h>
75 #include <openssl/objects.h>
76 #include <openssl/pem.h>
77
78 #define SECTION         "req"
79
80 #define BITS            "default_bits"
81 #define KEYFILE         "default_keyfile"
82 #define DISTINGUISHED_NAME      "distinguished_name"
83 #define ATTRIBUTES      "attributes"
84 #define V3_EXTENSIONS   "x509_extensions"
85 #define REQ_EXTENSIONS  "req_extensions"
86
87 #define DEFAULT_KEY_LENGTH      512
88 #define MIN_KEY_LENGTH          384
89
90 #undef PROG
91 #define PROG    req_main
92
93 /* -inform arg  - input format - default PEM (one of DER, TXT or PEM)
94  * -outform arg - output format - default PEM
95  * -in arg      - input file - default stdin
96  * -out arg     - output file - default stdout
97  * -verify      - check request signature
98  * -noout       - don't print stuff out.
99  * -text        - print out human readable text.
100  * -nodes       - no des encryption
101  * -config file - Load configuration file.
102  * -key file    - make a request using key in file (or use it for verification).
103  * -keyform     - key file format.
104  * -newkey      - make a key and a request.
105  * -modulus     - print RSA modulus.
106  * -x509        - output a self signed X509 structure instead.
107  * -asn1-kludge - output new certificate request in a format that some CA's
108  *                require.  This format is wrong
109  */
110
111 static int make_REQ(X509_REQ *req,EVP_PKEY *pkey,int attribs);
112 static int add_attribute_object(STACK_OF(X509_ATTRIBUTE) *n, char *text,
113                                 char *def, char *value, int nid, int min,
114                                 int max);
115 static int add_DN_object(X509_NAME *n, char *text, char *def, char *value,
116         int nid,int min,int max);
117 static void MS_CALLBACK req_cb(int p,int n,void *arg);
118 static int req_fix_data(int nid,int *type,int len,int min,int max);
119 static int check_end(char *str, char *end);
120 static int add_oid_section(LHASH *conf);
121 #ifndef MONOLITH
122 static char *default_config_file=NULL;
123 static LHASH *config=NULL;
124 #endif
125 static LHASH *req_conf=NULL;
126
127 #define TYPE_RSA        1
128 #define TYPE_DSA        2
129 #define TYPE_DH         3
130
131 int MAIN(int argc, char **argv)
132         {
133 #ifndef NO_DSA
134         DSA *dsa_params=NULL;
135 #endif
136         int ex=1,x509=0,days=30;
137         X509 *x509ss=NULL;
138         X509_REQ *req=NULL;
139         EVP_PKEY *pkey=NULL;
140         int i,badops=0,newreq=0,newkey= -1,pkey_type=0;
141         BIO *in=NULL,*out=NULL;
142         int informat,outformat,verify=0,noout=0,text=0,keyform=FORMAT_PEM;
143         int nodes=0,kludge=0;
144         char *infile,*outfile,*prog,*keyfile=NULL,*template=NULL,*keyout=NULL;
145         char *extensions = NULL;
146         char *req_exts = NULL;
147         EVP_CIPHER *cipher=NULL;
148         int modulus=0;
149         char *p;
150         const EVP_MD *md_alg=NULL,*digest=EVP_md5();
151 #ifndef MONOLITH
152         MS_STATIC char config_name[256];
153 #endif
154
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;
504                 char buffer[200];
505
506                 if ((randfile=CONF_get_string(req_conf,SECTION,"RANDFILE")) == NULL)
507                         randfile=RAND_file_name(buffer,200);
508 #ifdef WINDOWS
509                 BIO_printf(bio_err,"Loading 'screen' into random state -");
510                 BIO_flush(bio_err);
511                 RAND_screen();
512                 BIO_printf(bio_err," done\n");
513 #endif
514                 if ((randfile == NULL) || !RAND_load_file(randfile,1024L*1024L))
515                         {
516                         BIO_printf(bio_err,"unable to load 'random state'\n");
517                         BIO_printf(bio_err,"What this means is that the random number generator has not been seeded\n");
518                         BIO_printf(bio_err,"with much random data.\n");
519                         BIO_printf(bio_err,"Consider setting the RANDFILE environment variable to point at a file that\n");
520                         BIO_printf(bio_err,"'random' data can be kept in.\n");
521                         }
522                 if (newkey <= 0)
523                         {
524                         newkey=(int)CONF_get_number(req_conf,SECTION,BITS);
525                         if (newkey <= 0)
526                                 newkey=DEFAULT_KEY_LENGTH;
527                         }
528
529                 if (newkey < MIN_KEY_LENGTH)
530                         {
531                         BIO_printf(bio_err,"private key length is too short,\n");
532                         BIO_printf(bio_err,"it needs to be at least %d bits, not %d\n",MIN_KEY_LENGTH,newkey);
533                         goto end;
534                         }
535                 BIO_printf(bio_err,"Generating a %d bit %s private key\n",
536                         newkey,(pkey_type == TYPE_RSA)?"RSA":"DSA");
537
538                 if ((pkey=EVP_PKEY_new()) == NULL) goto end;
539
540 #ifndef NO_RSA
541                 if (pkey_type == TYPE_RSA)
542                         {
543                         if (!EVP_PKEY_assign_RSA(pkey,
544                                 RSA_generate_key(newkey,0x10001,
545                                         req_cb,bio_err)))
546                                 goto end;
547                         }
548                 else
549 #endif
550 #ifndef NO_DSA
551                         if (pkey_type == TYPE_DSA)
552                         {
553                         if (!DSA_generate_key(dsa_params)) goto end;
554                         if (!EVP_PKEY_assign_DSA(pkey,dsa_params)) goto end;
555                         dsa_params=NULL;
556                         }
557 #endif
558
559                 if ((randfile == NULL) || (RAND_write_file(randfile) == 0))
560                         BIO_printf(bio_err,"unable to write 'random state'\n");
561
562                 if (pkey == NULL) goto end;
563
564                 if (keyout == NULL)
565                         keyout=CONF_get_string(req_conf,SECTION,KEYFILE);
566
567                 if (keyout == NULL)
568                         {
569                         BIO_printf(bio_err,"writing new private key to stdout\n");
570                         BIO_set_fp(out,stdout,BIO_NOCLOSE);
571                         }
572                 else
573                         {
574                         BIO_printf(bio_err,"writing new private key to '%s'\n",keyout);
575                         if (BIO_write_filename(out,keyout) <= 0)
576                                 {
577                                 perror(keyout);
578                                 goto end;
579                                 }
580                         }
581
582                 p=CONF_get_string(req_conf,SECTION,"encrypt_rsa_key");
583                 if (p == NULL)
584                         p=CONF_get_string(req_conf,SECTION,"encrypt_key");
585                 if ((p != NULL) && (strcmp(p,"no") == 0))
586                         cipher=NULL;
587                 if (nodes) cipher=NULL;
588                 
589                 i=0;
590 loop:
591                 if (!PEM_write_bio_PrivateKey(out,pkey,cipher,
592                         NULL,0,NULL,NULL))
593                         {
594                         if ((ERR_GET_REASON(ERR_peek_error()) ==
595                                 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3))
596                                 {
597                                 ERR_clear_error();
598                                 i++;
599                                 goto loop;
600                                 }
601                         goto end;
602                         }
603                 BIO_printf(bio_err,"-----\n");
604                 }
605
606         if (!newreq)
607                 {
608                 /* Since we are using a pre-existing certificate
609                  * request, the kludge 'format' info should not be
610                  * changed. */
611                 kludge= -1;
612                 if (infile == NULL)
613                         BIO_set_fp(in,stdin,BIO_NOCLOSE);
614                 else
615                         {
616                         if (BIO_read_filename(in,infile) <= 0)
617                                 {
618                                 perror(infile);
619                                 goto end;
620                                 }
621                         }
622
623                 if      (informat == FORMAT_ASN1)
624                         req=d2i_X509_REQ_bio(in,NULL);
625                 else if (informat == FORMAT_PEM)
626                         req=PEM_read_bio_X509_REQ(in,NULL,NULL,NULL);
627                 else
628                         {
629                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
630                         goto end;
631                         }
632                 if (req == NULL)
633                         {
634                         BIO_printf(bio_err,"unable to load X509 request\n");
635                         goto end;
636                         }
637                 }
638
639         if (newreq || x509)
640                 {
641 #ifndef NO_DSA
642                 if (pkey->type == EVP_PKEY_DSA)
643                         digest=EVP_dss1();
644 #endif
645
646                 if (pkey == NULL)
647                         {
648                         BIO_printf(bio_err,"you need to specify a private key\n");
649                         goto end;
650                         }
651                 if (req == NULL)
652                         {
653                         req=X509_REQ_new();
654                         if (req == NULL)
655                                 {
656                                 goto end;
657                                 }
658
659                         i=make_REQ(req,pkey,!x509);
660                         if (kludge >= 0)
661                                 req->req_info->req_kludge=kludge;
662                         if (!i)
663                                 {
664                                 BIO_printf(bio_err,"problems making Certificate Request\n");
665                                 goto end;
666                                 }
667                         }
668                 if (x509)
669                         {
670                         EVP_PKEY *tmppkey;
671                         X509V3_CTX ext_ctx;
672                         if ((x509ss=X509_new()) == NULL) goto end;
673
674                         /* Set version to V3 */
675                         if(!X509_set_version(x509ss, 2)) goto end;
676                         ASN1_INTEGER_set(X509_get_serialNumber(x509ss),0L);
677
678                         X509_set_issuer_name(x509ss,
679                                 X509_REQ_get_subject_name(req));
680                         X509_gmtime_adj(X509_get_notBefore(x509ss),0);
681                         X509_gmtime_adj(X509_get_notAfter(x509ss),
682                                 (long)60*60*24*days);
683                         X509_set_subject_name(x509ss,
684                                 X509_REQ_get_subject_name(req));
685                         tmppkey = X509_REQ_get_pubkey(req);
686                         X509_set_pubkey(x509ss,tmppkey);
687                         EVP_PKEY_free(tmppkey);
688
689                         /* Set up V3 context struct */
690
691                         X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
692                         X509V3_set_conf_lhash(&ext_ctx, req_conf);
693
694                         /* Add extensions */
695                         if(extensions && !X509V3_EXT_add_conf(req_conf, 
696                                         &ext_ctx, extensions, x509ss))
697                             {
698                             BIO_printf(bio_err,
699                                        "Error Loading extension section %s\n",
700                                        extensions);
701                             goto end;
702                             }
703
704                         if (!(i=X509_sign(x509ss,pkey,digest)))
705                                 goto end;
706                         }
707                 else
708                         {
709                         X509V3_CTX ext_ctx;
710
711                         /* Set up V3 context struct */
712
713                         X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
714                         X509V3_set_conf_lhash(&ext_ctx, req_conf);
715
716                         /* Add extensions */
717                         if(req_exts && !X509V3_EXT_REQ_add_conf(req_conf, 
718                                         &ext_ctx, req_exts, req))
719                             {
720                             BIO_printf(bio_err,
721                                        "Error Loading extension section %s\n",
722                                        req_exts);
723                             goto end;
724                             }
725                         if (!(i=X509_REQ_sign(req,pkey,digest)))
726                                 goto end;
727                         }
728                 }
729
730         if (verify && !x509)
731                 {
732                 int tmp=0;
733
734                 if (pkey == NULL)
735                         {
736                         pkey=X509_REQ_get_pubkey(req);
737                         tmp=1;
738                         if (pkey == NULL) goto end;
739                         }
740
741                 i=X509_REQ_verify(req,pkey);
742                 if (tmp) {
743                         EVP_PKEY_free(pkey);
744                         pkey=NULL;
745                 }
746
747                 if (i < 0)
748                         {
749                         goto end;
750                         }
751                 else if (i == 0)
752                         {
753                         BIO_printf(bio_err,"verify failure\n");
754                         }
755                 else /* if (i > 0) */
756                         BIO_printf(bio_err,"verify OK\n");
757                 }
758
759         if (noout && !text && !modulus)
760                 {
761                 ex=0;
762                 goto end;
763                 }
764
765         if (outfile == NULL)
766                 BIO_set_fp(out,stdout,BIO_NOCLOSE);
767         else
768                 {
769                 if ((keyout != NULL) && (strcmp(outfile,keyout) == 0))
770                         i=(int)BIO_append_filename(out,outfile);
771                 else
772                         i=(int)BIO_write_filename(out,outfile);
773                 if (!i)
774                         {
775                         perror(outfile);
776                         goto end;
777                         }
778                 }
779
780         if (text)
781                 {
782                 if (x509)
783                         X509_print(out,x509ss);
784                 else    
785                         X509_REQ_print(out,req);
786                 }
787
788         if (modulus)
789                 {
790                 EVP_PKEY *pubkey;
791
792                 if (x509)
793                         pubkey=X509_get_pubkey(x509ss);
794                 else
795                         pubkey=X509_REQ_get_pubkey(req);
796                 if (pubkey == NULL)
797                         {
798                         fprintf(stdout,"Modulus=unavailable\n");
799                         goto end; 
800                         }
801                 fprintf(stdout,"Modulus=");
802 #ifndef NO_RSA
803                 if (pubkey->type == EVP_PKEY_RSA)
804                         BN_print(out,pubkey->pkey.rsa->n);
805                 else
806 #endif
807                         fprintf(stdout,"Wrong Algorithm type");
808                 fprintf(stdout,"\n");
809                 }
810
811         if (!noout && !x509)
812                 {
813                 if      (outformat == FORMAT_ASN1)
814                         i=i2d_X509_REQ_bio(out,req);
815                 else if (outformat == FORMAT_PEM)
816                         i=PEM_write_bio_X509_REQ(out,req);
817                 else    {
818                         BIO_printf(bio_err,"bad output format specified for outfile\n");
819                         goto end;
820                         }
821                 if (!i)
822                         {
823                         BIO_printf(bio_err,"unable to write X509 request\n");
824                         goto end;
825                         }
826                 }
827         if (!noout && x509 && (x509ss != NULL))
828                 {
829                 if      (outformat == FORMAT_ASN1)
830                         i=i2d_X509_bio(out,x509ss);
831                 else if (outformat == FORMAT_PEM)
832                         i=PEM_write_bio_X509(out,x509ss);
833                 else    {
834                         BIO_printf(bio_err,"bad output format specified for outfile\n");
835                         goto end;
836                         }
837                 if (!i)
838                         {
839                         BIO_printf(bio_err,"unable to write X509 certificate\n");
840                         goto end;
841                         }
842                 }
843         ex=0;
844 end:
845         if (ex)
846                 {
847                 ERR_print_errors(bio_err);
848                 }
849         if ((req_conf != NULL) && (req_conf != config)) CONF_free(req_conf);
850         BIO_free(in);
851         BIO_free(out);
852         EVP_PKEY_free(pkey);
853         X509_REQ_free(req);
854         X509_free(x509ss);
855         X509V3_EXT_cleanup();
856         OBJ_cleanup();
857 #ifndef NO_DSA
858         if (dsa_params != NULL) DSA_free(dsa_params);
859 #endif
860         EXIT(ex);
861         }
862
863 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, int attribs)
864         {
865         int ret=0,i;
866         char *p,*q;
867         X509_REQ_INFO *ri;
868         char buf[100];
869         int nid,min,max;
870         char *type,*def,*tmp,*value,*tmp_attr;
871         STACK_OF(CONF_VALUE) *sk, *attr=NULL;
872         CONF_VALUE *v;
873         
874         tmp=CONF_get_string(req_conf,SECTION,DISTINGUISHED_NAME);
875         if (tmp == NULL)
876                 {
877                 BIO_printf(bio_err,"unable to find '%s' in config\n",
878                         DISTINGUISHED_NAME);
879                 goto err;
880                 }
881         sk=CONF_get_section(req_conf,tmp);
882         if (sk == NULL)
883                 {
884                 BIO_printf(bio_err,"unable to get '%s' section\n",tmp);
885                 goto err;
886                 }
887
888         tmp_attr=CONF_get_string(req_conf,SECTION,ATTRIBUTES);
889         if (tmp_attr == NULL)
890                 attr=NULL;
891         else
892                 {
893                 attr=CONF_get_section(req_conf,tmp_attr);
894                 if (attr == NULL)
895                         {
896                         BIO_printf(bio_err,"unable to get '%s' section\n",tmp_attr);
897                         goto err;
898                         }
899                 }
900
901         ri=req->req_info;
902
903         BIO_printf(bio_err,"You are about to be asked to enter information that will be incorporated\n");
904         BIO_printf(bio_err,"into your certificate request.\n");
905         BIO_printf(bio_err,"What you are about to enter is what is called a Distinguished Name or a DN.\n");
906         BIO_printf(bio_err,"There are quite a few fields but you can leave some blank\n");
907         BIO_printf(bio_err,"For some fields there will be a default value,\n");
908         BIO_printf(bio_err,"If you enter '.', the field will be left blank.\n");
909         BIO_printf(bio_err,"-----\n");
910
911         /* setup version number */
912         if (!ASN1_INTEGER_set(ri->version,0L)) goto err; /* version 1 */
913
914         if (sk_CONF_VALUE_num(sk))
915                 {
916                 i= -1;
917 start:          for (;;)
918                         {
919                         i++;
920                         if (sk_CONF_VALUE_num(sk) <= i) break;
921
922                         v=sk_CONF_VALUE_value(sk,i);
923                         p=q=NULL;
924                         type=v->name;
925                         if(!check_end(type,"_min") || !check_end(type,"_max") ||
926                                 !check_end(type,"_default") ||
927                                          !check_end(type,"_value")) continue;
928                         /* Skip past any leading X. X: X, etc to allow for
929                          * multiple instances 
930                          */
931                         for(p = v->name; *p ; p++) 
932                                 if ((*p == ':') || (*p == ',') ||
933                                                          (*p == '.')) {
934                                         p++;
935                                         if(*p) type = p;
936                                         break;
937                                 }
938                         /* If OBJ not recognised ignore it */
939                         if ((nid=OBJ_txt2nid(type)) == NID_undef) goto start;
940                         sprintf(buf,"%s_default",v->name);
941                         if ((def=CONF_get_string(req_conf,tmp,buf)) == NULL)
942                                 def="";
943                                 
944                         sprintf(buf,"%s_value",v->name);
945                         if ((value=CONF_get_string(req_conf,tmp,buf)) == NULL)
946                                 value=NULL;
947
948                         sprintf(buf,"%s_min",v->name);
949                         min=(int)CONF_get_number(req_conf,tmp,buf);
950
951                         sprintf(buf,"%s_max",v->name);
952                         max=(int)CONF_get_number(req_conf,tmp,buf);
953
954                         if (!add_DN_object(ri->subject,v->value,def,value,nid,
955                                 min,max))
956                                 goto err;
957                         }
958                 if (sk_X509_NAME_ENTRY_num(ri->subject->entries) == 0)
959                         {
960                         BIO_printf(bio_err,"error, no objects specified in config file\n");
961                         goto err;
962                         }
963
964                 if (attribs)
965                         {
966                         if ((attr != NULL) && (sk_CONF_VALUE_num(attr) > 0))
967                                 {
968                                 BIO_printf(bio_err,"\nPlease enter the following 'extra' attributes\n");
969                                 BIO_printf(bio_err,"to be sent with your certificate request\n");
970                                 }
971
972                         i= -1;
973 start2:                 for (;;)
974                                 {
975                                 i++;
976                                 if ((attr == NULL) ||
977                                             (sk_CONF_VALUE_num(attr) <= i))
978                                         break;
979
980                                 v=sk_CONF_VALUE_value(attr,i);
981                                 type=v->name;
982                                 if ((nid=OBJ_txt2nid(type)) == NID_undef)
983                                         goto start2;
984
985                                 sprintf(buf,"%s_default",type);
986                                 if ((def=CONF_get_string(req_conf,tmp_attr,buf))
987                                         == NULL)
988                                         def="";
989                                 
990                                 sprintf(buf,"%s_value",type);
991                                 if ((value=CONF_get_string(req_conf,tmp_attr,buf))
992                                         == NULL)
993                                         value=NULL;
994
995                                 sprintf(buf,"%s_min",type);
996                                 min=(int)CONF_get_number(req_conf,tmp_attr,buf);
997
998                                 sprintf(buf,"%s_max",type);
999                                 max=(int)CONF_get_number(req_conf,tmp_attr,buf);
1000
1001                                 if (!add_attribute_object(ri->attributes,
1002                                         v->value,def,value,nid,min,max))
1003                                         goto err;
1004                                 }
1005                         }
1006                 }
1007         else
1008                 {
1009                 BIO_printf(bio_err,"No template, please set one up.\n");
1010                 goto err;
1011                 }
1012
1013         X509_REQ_set_pubkey(req,pkey);
1014
1015         ret=1;
1016 err:
1017         return(ret);
1018         }
1019
1020 static int add_DN_object(X509_NAME *n, char *text, char *def, char *value,
1021              int nid, int min, int max)
1022         {
1023         int i,j,ret=0;
1024         X509_NAME_ENTRY *ne=NULL;
1025         MS_STATIC char buf[1024];
1026
1027         BIO_printf(bio_err,"%s [%s]:",text,def);
1028         (void)BIO_flush(bio_err);
1029         if (value != NULL)
1030                 {
1031                 strcpy(buf,value);
1032                 strcat(buf,"\n");
1033                 BIO_printf(bio_err,"%s\n",value);
1034                 }
1035         else
1036                 {
1037                 buf[0]='\0';
1038                 fgets(buf,1024,stdin);
1039                 }
1040
1041         if (buf[0] == '\0') return(0);
1042         else if (buf[0] == '\n')
1043                 {
1044                 if ((def == NULL) || (def[0] == '\0'))
1045                         return(1);
1046                 strcpy(buf,def);
1047                 strcat(buf,"\n");
1048                 }
1049         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1050
1051         i=strlen(buf);
1052         if (buf[i-1] != '\n')
1053                 {
1054                 BIO_printf(bio_err,"weird input :-(\n");
1055                 return(0);
1056                 }
1057         buf[--i]='\0';
1058
1059         j=ASN1_PRINTABLE_type((unsigned char *)buf,-1);
1060         if (req_fix_data(nid,&j,i,min,max) == 0)
1061                 goto err;
1062 #ifdef CHARSET_EBCDIC
1063         ebcdic2ascii(buf, buf, i);
1064 #endif
1065         if ((ne=X509_NAME_ENTRY_create_by_NID(NULL,nid,j,(unsigned char *)buf,
1066                 strlen(buf)))
1067                 == NULL) goto err;
1068         if (!X509_NAME_add_entry(n,ne,X509_NAME_entry_count(n),0))
1069                 goto err;
1070
1071         ret=1;
1072 err:
1073         if (ne != NULL) X509_NAME_ENTRY_free(ne);
1074         return(ret);
1075         }
1076
1077 static int add_attribute_object(STACK_OF(X509_ATTRIBUTE) *n, char *text,
1078                                 char *def, char *value, int nid, int min,
1079                                 int max)
1080         {
1081         int i,z;
1082         X509_ATTRIBUTE *xa=NULL;
1083         static char buf[1024];
1084         ASN1_BIT_STRING *bs=NULL;
1085         ASN1_TYPE *at=NULL;
1086
1087 start:
1088         BIO_printf(bio_err,"%s [%s]:",text,def);
1089         (void)BIO_flush(bio_err);
1090         if (value != NULL)
1091                 {
1092                 strcpy(buf,value);
1093                 strcat(buf,"\n");
1094                 BIO_printf(bio_err,"%s\n",value);
1095                 }
1096         else
1097                 {
1098                 buf[0]='\0';
1099                 fgets(buf,1024,stdin);
1100                 }
1101
1102         if (buf[0] == '\0') return(0);
1103         else if (buf[0] == '\n')
1104                 {
1105                 if ((def == NULL) || (def[0] == '\0'))
1106                         return(1);
1107                 strcpy(buf,def);
1108                 strcat(buf,"\n");
1109                 }
1110         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1111
1112         i=strlen(buf);
1113         if (buf[i-1] != '\n')
1114                 {
1115                 BIO_printf(bio_err,"weird input :-(\n");
1116                 return(0);
1117                 }
1118         buf[--i]='\0';
1119
1120         /* add object plus value */
1121         if ((xa=X509_ATTRIBUTE_new()) == NULL)
1122                 goto err;
1123         if ((xa->value.set=sk_ASN1_TYPE_new_null()) == NULL)
1124                 goto err;
1125         xa->set=1;
1126
1127         if (xa->object != NULL) ASN1_OBJECT_free(xa->object);
1128         xa->object=OBJ_nid2obj(nid);
1129
1130         if ((bs=ASN1_BIT_STRING_new()) == NULL) goto err;
1131
1132         bs->type=ASN1_PRINTABLE_type((unsigned char *)buf,-1);
1133
1134         z=req_fix_data(nid,&bs->type,i,min,max);
1135         if (z == 0)
1136                 {
1137                 if (value == NULL)
1138                         goto start;
1139                 else    goto err;
1140                 }
1141
1142         if (!ASN1_STRING_set(bs,(unsigned char *)buf,i+1))
1143                 { BIO_printf(bio_err,"Malloc failure\n"); goto err; }
1144
1145         if ((at=ASN1_TYPE_new()) == NULL)
1146                 { BIO_printf(bio_err,"Malloc failure\n"); goto err; }
1147
1148         ASN1_TYPE_set(at,bs->type,(char *)bs);
1149         sk_ASN1_TYPE_push(xa->value.set,at);
1150         bs=NULL;
1151         at=NULL;
1152         /* only one item per attribute */
1153
1154         if (!sk_X509_ATTRIBUTE_push(n,xa)) goto err;
1155         return(1);
1156 err:
1157         if (xa != NULL) X509_ATTRIBUTE_free(xa);
1158         if (at != NULL) ASN1_TYPE_free(at);
1159         if (bs != NULL) ASN1_BIT_STRING_free(bs);
1160         return(0);
1161         }
1162
1163 static void MS_CALLBACK req_cb(int p, int n, void *arg)
1164         {
1165         char c='*';
1166
1167         if (p == 0) c='.';
1168         if (p == 1) c='+';
1169         if (p == 2) c='*';
1170         if (p == 3) c='\n';
1171         BIO_write((BIO *)arg,&c,1);
1172         (void)BIO_flush((BIO *)arg);
1173 #ifdef LINT
1174         p=n;
1175 #endif
1176         }
1177
1178 static int req_fix_data(int nid, int *type, int len, int min, int max)
1179         {
1180         if (nid == NID_pkcs9_emailAddress)
1181                 *type=V_ASN1_IA5STRING;
1182         if ((nid == NID_commonName) && (*type == V_ASN1_IA5STRING))
1183                 *type=V_ASN1_T61STRING;
1184         if ((nid == NID_pkcs9_challengePassword) &&
1185                 (*type == V_ASN1_IA5STRING))
1186                 *type=V_ASN1_T61STRING;
1187
1188         if ((nid == NID_pkcs9_unstructuredName) &&
1189                 (*type == V_ASN1_T61STRING))
1190                 {
1191                 BIO_printf(bio_err,"invalid characters in string, please re-enter the string\n");
1192                 return(0);
1193                 }
1194         if (nid == NID_pkcs9_unstructuredName)
1195                 *type=V_ASN1_IA5STRING;
1196
1197         if (len < min)
1198                 {
1199                 BIO_printf(bio_err,"string is too short, it needs to be at least %d bytes long\n",min);
1200                 return(0);
1201                 }
1202         if ((max != 0) && (len > max))
1203                 {
1204                 BIO_printf(bio_err,"string is too long, it needs to be less than  %d bytes long\n",max);
1205                 return(0);
1206                 }
1207         return(1);
1208         }
1209
1210 /* Check if the end of a string matches 'end' */
1211 static int check_end(char *str, char *end)
1212 {
1213         int elen, slen; 
1214         char *tmp;
1215         elen = strlen(end);
1216         slen = strlen(str);
1217         if(elen > slen) return 1;
1218         tmp = str + slen - elen;
1219         return strcmp(tmp, end);
1220 }
1221
1222 static int add_oid_section(LHASH *conf)
1223 {       
1224         char *p;
1225         STACK_OF(CONF_VALUE) *sktmp;
1226         CONF_VALUE *cnf;
1227         int i;
1228         if(!(p=CONF_get_string(conf,NULL,"oid_section"))) return 1;
1229         if(!(sktmp = CONF_get_section(conf, p))) {
1230                 BIO_printf(bio_err, "problem loading oid section %s\n", p);
1231                 return 0;
1232         }
1233         for(i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
1234                 cnf = sk_CONF_VALUE_value(sktmp, i);
1235                 if(OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
1236                         BIO_printf(bio_err, "problem creating object %s=%s\n",
1237                                                          cnf->name, cnf->value);
1238                         return 0;
1239                 }
1240         }
1241         return 1;
1242 }