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