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