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