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