const fixes
[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 /* Until the key-gen callbacks are modified to use newer prototypes, we allow
60  * deprecated functions for openssl-internal code */
61 #ifdef OPENSSL_NO_DEPRECATED
62 #undef OPENSSL_NO_DEPRECATED
63 #endif
64
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <time.h>
68 #include <string.h>
69 #ifdef OPENSSL_NO_STDIO
70 #define APPS_WIN16
71 #endif
72 #include "apps.h"
73 #include <openssl/bio.h>
74 #include <openssl/evp.h>
75 #include <openssl/conf.h>
76 #include <openssl/err.h>
77 #include <openssl/asn1.h>
78 #include <openssl/x509.h>
79 #include <openssl/x509v3.h>
80 #include <openssl/objects.h>
81 #include <openssl/pem.h>
82 #include "../crypto/cryptlib.h"
83
84 #define SECTION         "req"
85
86 #define BITS            "default_bits"
87 #define KEYFILE         "default_keyfile"
88 #define PROMPT          "prompt"
89 #define DISTINGUISHED_NAME      "distinguished_name"
90 #define ATTRIBUTES      "attributes"
91 #define V3_EXTENSIONS   "x509_extensions"
92 #define REQ_EXTENSIONS  "req_extensions"
93 #define STRING_MASK     "string_mask"
94 #define UTF8_IN         "utf8"
95
96 #define DEFAULT_KEY_LENGTH      512
97 #define MIN_KEY_LENGTH          384
98
99 #undef PROG
100 #define PROG    req_main
101
102 /* -inform arg  - input format - default PEM (DER or PEM)
103  * -outform arg - output format - default PEM
104  * -in arg      - input file - default stdin
105  * -out arg     - output file - default stdout
106  * -verify      - check request signature
107  * -noout       - don't print stuff out.
108  * -text        - print out human readable text.
109  * -nodes       - no des encryption
110  * -config file - Load configuration file.
111  * -key file    - make a request using key in file (or use it for verification).
112  * -keyform arg - key file format.
113  * -rand file(s) - load the file(s) into the PRNG.
114  * -newkey      - make a key and a request.
115  * -modulus     - print RSA modulus.
116  * -pubkey      - output Public Key.
117  * -x509        - output a self signed X509 structure instead.
118  * -asn1-kludge - output new certificate request in a format that some CA's
119  *                require.  This format is wrong
120  */
121
122 static int make_REQ(X509_REQ *req,EVP_PKEY *pkey,char *dn,int mutlirdn,
123                 int attribs,unsigned long chtype);
124 static int build_subject(X509_REQ *req, char *subj, unsigned long chtype,
125                 int multirdn);
126 static int prompt_info(X509_REQ *req,
127                 STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
128                 STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect, int attribs,
129                 unsigned long chtype);
130 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
131                                 STACK_OF(CONF_VALUE) *attr, int attribs,
132                                 unsigned long chtype);
133 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
134                                 char *value, int nid, int n_min,
135                                 int n_max, unsigned long chtype);
136 static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value,
137         int nid,int n_min,int n_max, unsigned long chtype, int mval);
138 #ifndef OPENSSL_NO_RSA
139 static int MS_CALLBACK req_cb(int p, int n, BN_GENCB *cb);
140 #endif
141 static int req_check_len(int len,int n_min,int n_max);
142 static int check_end(const char *str, const char *end);
143 #ifndef MONOLITH
144 static char *default_config_file=NULL;
145 #endif
146 static CONF *req_conf=NULL;
147 static int batch=0;
148
149 #define TYPE_RSA        1
150 #define TYPE_DSA        2
151 #define TYPE_DH         3
152 #define TYPE_EC         4
153
154 int MAIN(int, char **);
155
156 int MAIN(int argc, char **argv)
157         {
158         ENGINE *e = NULL;
159 #ifndef OPENSSL_NO_DSA
160         DSA *dsa_params=NULL;
161 #endif
162 #ifndef OPENSSL_NO_ECDSA
163         EC_KEY *ec_params = NULL;
164 #endif
165         unsigned long nmflag = 0, reqflag = 0;
166         int ex=1,x509=0,days=30;
167         X509 *x509ss=NULL;
168         X509_REQ *req=NULL;
169         EVP_PKEY *pkey=NULL;
170         int i=0,badops=0,newreq=0,verbose=0,pkey_type=TYPE_RSA;
171         long newkey = -1;
172         BIO *in=NULL,*out=NULL;
173         int informat,outformat,verify=0,noout=0,text=0,keyform=FORMAT_PEM;
174         int nodes=0,kludge=0,newhdr=0,subject=0,pubkey=0;
175         char *infile,*outfile,*prog,*keyfile=NULL,*template=NULL,*keyout=NULL;
176 #ifndef OPENSSL_NO_ENGINE
177         char *engine=NULL;
178 #endif
179         char *extensions = NULL;
180         char *req_exts = NULL;
181         const EVP_CIPHER *cipher=NULL;
182         ASN1_INTEGER *serial = NULL;
183         int modulus=0;
184         char *inrand=NULL;
185         char *passargin = NULL, *passargout = NULL;
186         char *passin = NULL, *passout = NULL;
187         char *p;
188         char *subj = NULL;
189         int multirdn = 0;
190         const EVP_MD *md_alg=NULL,*digest=EVP_sha1();
191         unsigned long chtype = MBSTRING_ASC;
192 #ifndef MONOLITH
193         char *to_free;
194         long errline;
195 #endif
196
197         req_conf = NULL;
198 #ifndef OPENSSL_NO_DES
199         cipher=EVP_des_ede3_cbc();
200 #endif
201         apps_startup();
202
203         if (bio_err == NULL)
204                 if ((bio_err=BIO_new(BIO_s_file())) != NULL)
205                         BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);
206
207         infile=NULL;
208         outfile=NULL;
209         informat=FORMAT_PEM;
210         outformat=FORMAT_PEM;
211
212         prog=argv[0];
213         argc--;
214         argv++;
215         while (argc >= 1)
216                 {
217                 if      (strcmp(*argv,"-inform") == 0)
218                         {
219                         if (--argc < 1) goto bad;
220                         informat=str2fmt(*(++argv));
221                         }
222                 else if (strcmp(*argv,"-outform") == 0)
223                         {
224                         if (--argc < 1) goto bad;
225                         outformat=str2fmt(*(++argv));
226                         }
227 #ifndef OPENSSL_NO_ENGINE
228                 else if (strcmp(*argv,"-engine") == 0)
229                         {
230                         if (--argc < 1) goto bad;
231                         engine= *(++argv);
232                         }
233 #endif
234                 else if (strcmp(*argv,"-key") == 0)
235                         {
236                         if (--argc < 1) goto bad;
237                         keyfile= *(++argv);
238                         }
239                 else if (strcmp(*argv,"-pubkey") == 0)
240                         {
241                         pubkey=1;
242                         }
243                 else if (strcmp(*argv,"-new") == 0)
244                         {
245                         newreq=1;
246                         }
247                 else if (strcmp(*argv,"-config") == 0)
248                         {       
249                         if (--argc < 1) goto bad;
250                         template= *(++argv);
251                         }
252                 else if (strcmp(*argv,"-keyform") == 0)
253                         {
254                         if (--argc < 1) goto bad;
255                         keyform=str2fmt(*(++argv));
256                         }
257                 else if (strcmp(*argv,"-in") == 0)
258                         {
259                         if (--argc < 1) goto bad;
260                         infile= *(++argv);
261                         }
262                 else if (strcmp(*argv,"-out") == 0)
263                         {
264                         if (--argc < 1) goto bad;
265                         outfile= *(++argv);
266                         }
267                 else if (strcmp(*argv,"-keyout") == 0)
268                         {
269                         if (--argc < 1) goto bad;
270                         keyout= *(++argv);
271                         }
272                 else if (strcmp(*argv,"-passin") == 0)
273                         {
274                         if (--argc < 1) goto bad;
275                         passargin= *(++argv);
276                         }
277                 else if (strcmp(*argv,"-passout") == 0)
278                         {
279                         if (--argc < 1) goto bad;
280                         passargout= *(++argv);
281                         }
282                 else if (strcmp(*argv,"-rand") == 0)
283                         {
284                         if (--argc < 1) goto bad;
285                         inrand= *(++argv);
286                         }
287                 else if (strcmp(*argv,"-newkey") == 0)
288                         {
289                         int is_numeric;
290
291                         if (--argc < 1) goto bad;
292                         p= *(++argv);
293                         is_numeric = p[0] >= '0' && p[0] <= '9';
294                         if (strncmp("rsa:",p,4) == 0 || is_numeric)
295                                 {
296                                 pkey_type=TYPE_RSA;
297                                 if(!is_numeric)
298                                     p+=4;
299                                 newkey= atoi(p);
300                                 }
301                         else
302 #ifndef OPENSSL_NO_DSA
303                                 if (strncmp("dsa:",p,4) == 0)
304                                 {
305                                 X509 *xtmp=NULL;
306                                 EVP_PKEY *dtmp;
307
308                                 pkey_type=TYPE_DSA;
309                                 p+=4;
310                                 if ((in=BIO_new_file(p,"r")) == NULL)
311                                         {
312                                         perror(p);
313                                         goto end;
314                                         }
315                                 if ((dsa_params=PEM_read_bio_DSAparams(in,NULL,NULL,NULL)) == NULL)
316                                         {
317                                         ERR_clear_error();
318                                         (void)BIO_reset(in);
319                                         if ((xtmp=PEM_read_bio_X509(in,NULL,NULL,NULL)) == NULL)
320                                                 {
321                                                 BIO_printf(bio_err,"unable to load DSA parameters from file\n");
322                                                 goto end;
323                                                 }
324
325                                         if ((dtmp=X509_get_pubkey(xtmp)) == NULL) goto end;
326                                         if (dtmp->type == EVP_PKEY_DSA)
327                                                 dsa_params=DSAparams_dup(dtmp->pkey.dsa);
328                                         EVP_PKEY_free(dtmp);
329                                         X509_free(xtmp);
330                                         if (dsa_params == NULL)
331                                                 {
332                                                 BIO_printf(bio_err,"Certificate does not contain DSA parameters\n");
333                                                 goto end;
334                                                 }
335                                         }
336                                 BIO_free(in);
337                                 in=NULL;
338                                 newkey=BN_num_bits(dsa_params->p);
339                                 }
340                         else 
341 #endif
342 #ifndef OPENSSL_NO_ECDSA
343                                 if (strncmp("ec:",p,3) == 0)
344                                 {
345                                 X509 *xtmp=NULL;
346                                 EVP_PKEY *dtmp;
347
348                                 pkey_type=TYPE_EC;
349                                 p+=3;
350                                 if ((in=BIO_new_file(p,"r")) == NULL)
351                                         {
352                                         perror(p);
353                                         goto end;
354                                         }
355                                 if ((ec_params = EC_KEY_new()) == NULL)
356                                         goto end;
357                                 if ((ec_params->group = PEM_read_bio_ECPKParameters(in, NULL, NULL, NULL)) == NULL)
358                                         {
359                                         if (ec_params)
360                                                 EC_KEY_free(ec_params);
361                                         ERR_clear_error();
362                                         (void)BIO_reset(in);
363                                         if ((xtmp=PEM_read_bio_X509(in,NULL,NULL,NULL)) == NULL)
364                                                 {       
365                                                 BIO_printf(bio_err,"unable to load EC parameters from file\n");
366                                                 goto end;
367                                                 }
368
369                                         if ((dtmp=X509_get_pubkey(xtmp))==NULL)
370                                                 goto end;
371                                         if (dtmp->type == EVP_PKEY_EC)
372                                                 ec_params = ECParameters_dup(dtmp->pkey.eckey);
373                                         EVP_PKEY_free(dtmp);
374                                         X509_free(xtmp);
375                                         if (ec_params == NULL)
376                                                 {
377                                                 BIO_printf(bio_err,"Certificate does not contain EC parameters\n");
378                                                 goto end;
379                                                 }
380                                         }
381
382                                 BIO_free(in);
383                                 in=NULL;
384                                 
385                                 newkey = EC_GROUP_get_degree(ec_params->group);
386
387                                 }
388                         else
389 #endif
390 #ifndef OPENSSL_NO_DH
391                                 if (strncmp("dh:",p,4) == 0)
392                                 {
393                                 pkey_type=TYPE_DH;
394                                 p+=3;
395                                 }
396                         else
397 #endif
398                                 {
399                                 goto bad;
400                                 }
401
402                         newreq=1;
403                         }
404                 else if (strcmp(*argv,"-batch") == 0)
405                         batch=1;
406                 else if (strcmp(*argv,"-newhdr") == 0)
407                         newhdr=1;
408                 else if (strcmp(*argv,"-modulus") == 0)
409                         modulus=1;
410                 else if (strcmp(*argv,"-verify") == 0)
411                         verify=1;
412                 else if (strcmp(*argv,"-nodes") == 0)
413                         nodes=1;
414                 else if (strcmp(*argv,"-noout") == 0)
415                         noout=1;
416                 else if (strcmp(*argv,"-verbose") == 0)
417                         verbose=1;
418                 else if (strcmp(*argv,"-utf8") == 0)
419                         chtype = MBSTRING_UTF8;
420                 else if (strcmp(*argv,"-nameopt") == 0)
421                         {
422                         if (--argc < 1) goto bad;
423                         if (!set_name_ex(&nmflag, *(++argv))) goto bad;
424                         }
425                 else if (strcmp(*argv,"-reqopt") == 0)
426                         {
427                         if (--argc < 1) goto bad;
428                         if (!set_cert_ex(&reqflag, *(++argv))) goto bad;
429                         }
430                 else if (strcmp(*argv,"-subject") == 0)
431                         subject=1;
432                 else if (strcmp(*argv,"-text") == 0)
433                         text=1;
434                 else if (strcmp(*argv,"-x509") == 0)
435                         x509=1;
436                 else if (strcmp(*argv,"-asn1-kludge") == 0)
437                         kludge=1;
438                 else if (strcmp(*argv,"-no-asn1-kludge") == 0)
439                         kludge=0;
440                 else if (strcmp(*argv,"-subj") == 0)
441                         {
442                         if (--argc < 1) goto bad;
443                         subj= *(++argv);
444                         }
445                 else if (strcmp(*argv,"-multivalue-rdn") == 0)
446                         multirdn=1;
447                 else if (strcmp(*argv,"-days") == 0)
448                         {
449                         if (--argc < 1) goto bad;
450                         days= atoi(*(++argv));
451                         if (days == 0) days=30;
452                         }
453                 else if (strcmp(*argv,"-set_serial") == 0)
454                         {
455                         if (--argc < 1) goto bad;
456                         serial = s2i_ASN1_INTEGER(NULL, *(++argv));
457                         if (!serial) goto bad;
458                         }
459                 else if ((md_alg=EVP_get_digestbyname(&((*argv)[1]))) != NULL)
460                         {
461                         /* ok */
462                         digest=md_alg;
463                         }
464                 else if (strcmp(*argv,"-extensions") == 0)
465                         {
466                         if (--argc < 1) goto bad;
467                         extensions = *(++argv);
468                         }
469                 else if (strcmp(*argv,"-reqexts") == 0)
470                         {
471                         if (--argc < 1) goto bad;
472                         req_exts = *(++argv);
473                         }
474                 else
475                         {
476                         BIO_printf(bio_err,"unknown option %s\n",*argv);
477                         badops=1;
478                         break;
479                         }
480                 argc--;
481                 argv++;
482                 }
483
484         if (badops)
485                 {
486 bad:
487                 BIO_printf(bio_err,"%s [options] <infile >outfile\n",prog);
488                 BIO_printf(bio_err,"where options  are\n");
489                 BIO_printf(bio_err," -inform arg    input format - DER or PEM\n");
490                 BIO_printf(bio_err," -outform arg   output format - DER or PEM\n");
491                 BIO_printf(bio_err," -in arg        input file\n");
492                 BIO_printf(bio_err," -out arg       output file\n");
493                 BIO_printf(bio_err," -text          text form of request\n");
494                 BIO_printf(bio_err," -pubkey        output public key\n");
495                 BIO_printf(bio_err," -noout         do not output REQ\n");
496                 BIO_printf(bio_err," -verify        verify signature on REQ\n");
497                 BIO_printf(bio_err," -modulus       RSA modulus\n");
498                 BIO_printf(bio_err," -nodes         don't encrypt the output key\n");
499 #ifndef OPENSSL_NO_ENGINE
500                 BIO_printf(bio_err," -engine e      use engine e, possibly a hardware device\n");
501 #endif
502                 BIO_printf(bio_err," -subject       output the request's subject\n");
503                 BIO_printf(bio_err," -passin        private key password source\n");
504                 BIO_printf(bio_err," -key file      use the private key contained in file\n");
505                 BIO_printf(bio_err," -keyform arg   key file format\n");
506                 BIO_printf(bio_err," -keyout arg    file to send the key to\n");
507                 BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
508                 BIO_printf(bio_err,"                load the file (or the files in the directory) into\n");
509                 BIO_printf(bio_err,"                the random number generator\n");
510                 BIO_printf(bio_err," -newkey rsa:bits generate a new RSA key of 'bits' in size\n");
511                 BIO_printf(bio_err," -newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'\n");
512 #ifndef OPENSSL_NO_ECDSA
513                 BIO_printf(bio_err," -newkey ec:file generate a new EC key, parameters taken from CA in 'file'\n");
514 #endif
515                 BIO_printf(bio_err," -[digest]      Digest to sign with (md5, sha1, md2, mdc2, md4)\n");
516                 BIO_printf(bio_err," -config file   request template file.\n");
517                 BIO_printf(bio_err," -subj arg      set or modify request subject\n");
518                 BIO_printf(bio_err," -multivalue-rdn enable support for multivalued RDNs\n");
519                 BIO_printf(bio_err," -new           new request.\n");
520                 BIO_printf(bio_err," -batch         do not ask anything during request generation\n");
521                 BIO_printf(bio_err," -x509          output a x509 structure instead of a cert. req.\n");
522                 BIO_printf(bio_err," -days          number of days a certificate generated by -x509 is valid for.\n");
523                 BIO_printf(bio_err," -set_serial    serial number to use for a certificate generated by -x509.\n");
524                 BIO_printf(bio_err," -newhdr        output \"NEW\" in the header lines\n");
525                 BIO_printf(bio_err," -asn1-kludge   Output the 'request' in a format that is wrong but some CA's\n");
526                 BIO_printf(bio_err,"                have been reported as requiring\n");
527                 BIO_printf(bio_err," -extensions .. specify certificate extension section (override value in config file)\n");
528                 BIO_printf(bio_err," -reqexts ..    specify request extension section (override value in config file)\n");
529                 BIO_printf(bio_err," -utf8          input characters are UTF8 (default ASCII)\n");
530                 BIO_printf(bio_err," -nameopt arg    - various certificate name options\n");
531                 BIO_printf(bio_err," -reqopt arg    - various request text options\n\n");
532                 goto end;
533                 }
534
535         ERR_load_crypto_strings();
536         if(!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
537                 BIO_printf(bio_err, "Error getting passwords\n");
538                 goto end;
539         }
540
541 #ifndef MONOLITH /* else this has happened in openssl.c (global `config') */
542         /* Lets load up our environment a little */
543         p=getenv("OPENSSL_CONF");
544         if (p == NULL)
545                 p=getenv("SSLEAY_CONF");
546         if (p == NULL)
547                 p=to_free=make_config_name();
548         default_config_file=p;
549         config=NCONF_new(NULL);
550         i=NCONF_load(config, p, &errline);
551 #endif
552
553         if (template != NULL)
554                 {
555                 long errline = -1;
556
557                 if( verbose )
558                         BIO_printf(bio_err,"Using configuration from %s\n",template);
559                 req_conf=NCONF_new(NULL);
560                 i=NCONF_load(req_conf,template,&errline);
561                 if (i == 0)
562                         {
563                         BIO_printf(bio_err,"error on line %ld of %s\n",errline,template);
564                         goto end;
565                         }
566                 }
567         else
568                 {
569                 req_conf=config;
570
571                 if (req_conf == NULL)
572                         {
573                         BIO_printf(bio_err,"Unable to load config info from %s\n", default_config_file);
574                         if (newreq)
575                                 goto end;
576                         }
577                 else if( verbose )
578                         BIO_printf(bio_err,"Using configuration from %s\n",
579                         default_config_file);
580                 }
581
582         if (req_conf != NULL)
583                 {
584                 if (!load_config(bio_err, req_conf))
585                         goto end;
586                 p=NCONF_get_string(req_conf,NULL,"oid_file");
587                 if (p == NULL)
588                         ERR_clear_error();
589                 if (p != NULL)
590                         {
591                         BIO *oid_bio;
592
593                         oid_bio=BIO_new_file(p,"r");
594                         if (oid_bio == NULL) 
595                                 {
596                                 /*
597                                 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
598                                 ERR_print_errors(bio_err);
599                                 */
600                                 }
601                         else
602                                 {
603                                 OBJ_create_objects(oid_bio);
604                                 BIO_free(oid_bio);
605                                 }
606                         }
607                 }
608         if(!add_oid_section(bio_err, req_conf)) goto end;
609
610         if (md_alg == NULL)
611                 {
612                 p=NCONF_get_string(req_conf,SECTION,"default_md");
613                 if (p == NULL)
614                         ERR_clear_error();
615                 if (p != NULL)
616                         {
617                         if ((md_alg=EVP_get_digestbyname(p)) != NULL)
618                                 digest=md_alg;
619                         }
620                 }
621
622         if (!extensions)
623                 {
624                 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
625                 if (!extensions)
626                         ERR_clear_error();
627                 }
628         if (extensions) {
629                 /* Check syntax of file */
630                 X509V3_CTX ctx;
631                 X509V3_set_ctx_test(&ctx);
632                 X509V3_set_nconf(&ctx, req_conf);
633                 if(!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
634                         BIO_printf(bio_err,
635                          "Error Loading extension section %s\n", extensions);
636                         goto end;
637                 }
638         }
639
640         if(!passin)
641                 {
642                 passin = NCONF_get_string(req_conf, SECTION, "input_password");
643                 if (!passin)
644                         ERR_clear_error();
645                 }
646         
647         if(!passout)
648                 {
649                 passout = NCONF_get_string(req_conf, SECTION, "output_password");
650                 if (!passout)
651                         ERR_clear_error();
652                 }
653
654         p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
655         if (!p)
656                 ERR_clear_error();
657
658         if(p && !ASN1_STRING_set_default_mask_asc(p)) {
659                 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
660                 goto end;
661         }
662
663         if (chtype != MBSTRING_UTF8)
664                 {
665                 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
666                 if (!p)
667                         ERR_clear_error();
668                 else if (!strcmp(p, "yes"))
669                         chtype = MBSTRING_UTF8;
670                 }
671
672
673         if(!req_exts)
674                 {
675                 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
676                 if (!req_exts)
677                         ERR_clear_error();
678                 }
679         if(req_exts) {
680                 /* Check syntax of file */
681                 X509V3_CTX ctx;
682                 X509V3_set_ctx_test(&ctx);
683                 X509V3_set_nconf(&ctx, req_conf);
684                 if(!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
685                         BIO_printf(bio_err,
686                          "Error Loading request extension section %s\n",
687                                                                 req_exts);
688                         goto end;
689                 }
690         }
691
692         in=BIO_new(BIO_s_file());
693         out=BIO_new(BIO_s_file());
694         if ((in == NULL) || (out == NULL))
695                 goto end;
696
697 #ifndef OPENSSL_NO_ENGINE
698         e = setup_engine(bio_err, engine, 0);
699 #endif
700
701         if (keyfile != NULL)
702                 {
703                 pkey = load_key(bio_err, keyfile, keyform, 0, passin, e,
704                         "Private Key");
705                 if (!pkey)
706                         {
707                         /* load_key() has already printed an appropriate
708                            message */
709                         goto end;
710                         }
711                 if (EVP_PKEY_type(pkey->type) == EVP_PKEY_DSA || 
712                         EVP_PKEY_type(pkey->type) == EVP_PKEY_EC)
713                         {
714                         char *randfile = NCONF_get_string(req_conf,SECTION,"RANDFILE");
715                         if (randfile == NULL)
716                                 ERR_clear_error();
717                         app_RAND_load_file(randfile, bio_err, 0);
718                         }
719                 }
720
721         if (newreq && (pkey == NULL))
722                 {
723                 BN_GENCB cb;
724                 char *randfile = NCONF_get_string(req_conf,SECTION,"RANDFILE");
725                 if (randfile == NULL)
726                         ERR_clear_error();
727                 app_RAND_load_file(randfile, bio_err, 0);
728                 if (inrand)
729                         app_RAND_load_files(inrand);
730         
731                 if (newkey <= 0)
732                         {
733                         if (!NCONF_get_number(req_conf,SECTION,BITS, &newkey))
734                                 newkey=DEFAULT_KEY_LENGTH;
735                         }
736
737                 if (newkey < MIN_KEY_LENGTH && (pkey_type == TYPE_RSA || pkey_type == TYPE_DSA))
738                         {
739                         BIO_printf(bio_err,"private key length is too short,\n");
740                         BIO_printf(bio_err,"it needs to be at least %d bits, not %ld\n",MIN_KEY_LENGTH,newkey);
741                         goto end;
742                         }
743                 BIO_printf(bio_err,"Generating a %ld bit %s private key\n",
744                         newkey,(pkey_type == TYPE_RSA)?"RSA":
745                         (pkey_type == TYPE_DSA)?"DSA":"EC");
746
747                 if ((pkey=EVP_PKEY_new()) == NULL) goto end;
748
749 #ifndef OPENSSL_NO_RSA
750                 BN_GENCB_set(&cb, req_cb, bio_err);
751                 if (pkey_type == TYPE_RSA)
752                         {
753                         RSA *rsa = RSA_new();
754                         BIGNUM *bn = BN_new();
755                         if(!bn || !rsa || !BN_set_word(bn, 0x10001) ||
756                                         !RSA_generate_key_ex(rsa, newkey, bn, &cb) ||
757                                         !EVP_PKEY_assign_RSA(pkey, rsa))
758                                 {
759                                 if(bn) BN_free(bn);
760                                 if(rsa) RSA_free(rsa);
761                                 goto end;
762                                 }
763                         BN_free(bn);
764                         }
765                 else
766 #endif
767 #ifndef OPENSSL_NO_DSA
768                         if (pkey_type == TYPE_DSA)
769                         {
770                         if (!DSA_generate_key(dsa_params)) goto end;
771                         if (!EVP_PKEY_assign_DSA(pkey,dsa_params)) goto end;
772                         dsa_params=NULL;
773                         }
774 #endif
775 #ifndef OPENSSL_NO_ECDSA
776                         if (pkey_type == TYPE_EC)
777                         {
778                         if (!EC_KEY_generate_key(ec_params)) goto end;
779                         if (!EVP_PKEY_assign_EC_KEY(pkey, ec_params)) 
780                                 goto end;
781                         ec_params = NULL;
782                         }
783 #endif
784
785                 app_RAND_write_file(randfile, bio_err);
786
787                 if (pkey == NULL) goto end;
788
789                 if (keyout == NULL)
790                         {
791                         keyout=NCONF_get_string(req_conf,SECTION,KEYFILE);
792                         if (keyout == NULL)
793                                 ERR_clear_error();
794                         }
795                 
796                 if (keyout == NULL)
797                         {
798                         BIO_printf(bio_err,"writing new private key to stdout\n");
799                         BIO_set_fp(out,stdout,BIO_NOCLOSE);
800 #ifdef OPENSSL_SYS_VMS
801                         {
802                         BIO *tmpbio = BIO_new(BIO_f_linebuffer());
803                         out = BIO_push(tmpbio, out);
804                         }
805 #endif
806                         }
807                 else
808                         {
809                         BIO_printf(bio_err,"writing new private key to '%s'\n",keyout);
810                         if (BIO_write_filename(out,keyout) <= 0)
811                                 {
812                                 perror(keyout);
813                                 goto end;
814                                 }
815                         }
816
817                 p=NCONF_get_string(req_conf,SECTION,"encrypt_rsa_key");
818                 if (p == NULL)
819                         {
820                         ERR_clear_error();
821                         p=NCONF_get_string(req_conf,SECTION,"encrypt_key");
822                         if (p == NULL)
823                                 ERR_clear_error();
824                         }
825                 if ((p != NULL) && (strcmp(p,"no") == 0))
826                         cipher=NULL;
827                 if (nodes) cipher=NULL;
828                 
829                 i=0;
830 loop:
831                 if (!PEM_write_bio_PrivateKey(out,pkey,cipher,
832                         NULL,0,NULL,passout))
833                         {
834                         if ((ERR_GET_REASON(ERR_peek_error()) ==
835                                 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3))
836                                 {
837                                 ERR_clear_error();
838                                 i++;
839                                 goto loop;
840                                 }
841                         goto end;
842                         }
843                 BIO_printf(bio_err,"-----\n");
844                 }
845
846         if (!newreq)
847                 {
848                 /* Since we are using a pre-existing certificate
849                  * request, the kludge 'format' info should not be
850                  * changed. */
851                 kludge= -1;
852                 if (infile == NULL)
853                         BIO_set_fp(in,stdin,BIO_NOCLOSE);
854                 else
855                         {
856                         if (BIO_read_filename(in,infile) <= 0)
857                                 {
858                                 perror(infile);
859                                 goto end;
860                                 }
861                         }
862
863                 if      (informat == FORMAT_ASN1)
864                         req=d2i_X509_REQ_bio(in,NULL);
865                 else if (informat == FORMAT_PEM)
866                         req=PEM_read_bio_X509_REQ(in,NULL,NULL,NULL);
867                 else
868                         {
869                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
870                         goto end;
871                         }
872                 if (req == NULL)
873                         {
874                         BIO_printf(bio_err,"unable to load X509 request\n");
875                         goto end;
876                         }
877                 }
878
879         if (newreq || x509)
880                 {
881                 if (pkey == NULL)
882                         {
883                         BIO_printf(bio_err,"you need to specify a private key\n");
884                         goto end;
885                         }
886 #ifndef OPENSSL_NO_DSA
887                 if (pkey->type == EVP_PKEY_DSA)
888                         digest=EVP_dss1();
889 #endif
890 #ifndef OPENSSL_NO_ECDSA
891                 if (pkey->type == EVP_PKEY_EC)
892                         digest=EVP_ecdsa();
893 #endif
894                 if (req == NULL)
895                         {
896                         req=X509_REQ_new();
897                         if (req == NULL)
898                                 {
899                                 goto end;
900                                 }
901
902                         i=make_REQ(req,pkey,subj,multirdn,!x509, chtype);
903                         subj=NULL; /* done processing '-subj' option */
904                         if ((kludge > 0) && !sk_X509_ATTRIBUTE_num(req->req_info->attributes))
905                                 {
906                                 sk_X509_ATTRIBUTE_free(req->req_info->attributes);
907                                 req->req_info->attributes = NULL;
908                                 }
909                         if (!i)
910                                 {
911                                 BIO_printf(bio_err,"problems making Certificate Request\n");
912                                 goto end;
913                                 }
914                         }
915                 if (x509)
916                         {
917                         EVP_PKEY *tmppkey;
918                         X509V3_CTX ext_ctx;
919                         if ((x509ss=X509_new()) == NULL) goto end;
920
921                         /* Set version to V3 */
922                         if(extensions && !X509_set_version(x509ss, 2)) goto end;
923                         if (serial)
924                                 {
925                                 if (!X509_set_serialNumber(x509ss, serial)) goto end;
926                                 }
927                         else
928                                 {
929                                 if (!rand_serial(NULL,
930                                         X509_get_serialNumber(x509ss)))
931                                                 goto end;
932                                 }
933
934                         if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req))) goto end;
935                         if (!X509_gmtime_adj(X509_get_notBefore(x509ss),0)) goto end;
936                         if (!X509_gmtime_adj(X509_get_notAfter(x509ss), (long)60*60*24*days)) goto end;
937                         if (!X509_set_subject_name(x509ss, X509_REQ_get_subject_name(req))) goto end;
938                         tmppkey = X509_REQ_get_pubkey(req);
939                         if (!tmppkey || !X509_set_pubkey(x509ss,tmppkey)) goto end;
940                         EVP_PKEY_free(tmppkey);
941
942                         /* Set up V3 context struct */
943
944                         X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
945                         X509V3_set_nconf(&ext_ctx, req_conf);
946
947                         /* Add extensions */
948                         if(extensions && !X509V3_EXT_add_nconf(req_conf, 
949                                         &ext_ctx, extensions, x509ss))
950                                 {
951                                 BIO_printf(bio_err,
952                                         "Error Loading extension section %s\n",
953                                         extensions);
954                                 goto end;
955                                 }
956                         
957                         if (!(i=X509_sign(x509ss,pkey,digest)))
958                                 goto end;
959                         }
960                 else
961                         {
962                         X509V3_CTX ext_ctx;
963
964                         /* Set up V3 context struct */
965
966                         X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
967                         X509V3_set_nconf(&ext_ctx, req_conf);
968
969                         /* Add extensions */
970                         if(req_exts && !X509V3_EXT_REQ_add_nconf(req_conf, 
971                                         &ext_ctx, req_exts, req))
972                                 {
973                                 BIO_printf(bio_err,
974                                         "Error Loading extension section %s\n",
975                                         req_exts);
976                                 goto end;
977                                 }
978                         if (!(i=X509_REQ_sign(req,pkey,digest)))
979                                 goto end;
980                         }
981                 }
982
983         if (subj && x509)
984                 {
985                 BIO_printf(bio_err, "Cannot modifiy certificate subject\n");
986                 goto end;
987                 }
988
989         if (subj && !x509)
990                 {
991                 if (verbose)
992                         {
993                         BIO_printf(bio_err, "Modifying Request's Subject\n");
994                         print_name(bio_err, "old subject=", X509_REQ_get_subject_name(req), nmflag);
995                         }
996
997                 if (build_subject(req, subj, chtype, multirdn) == 0)
998                         {
999                         BIO_printf(bio_err, "ERROR: cannot modify subject\n");
1000                         ex=1;
1001                         goto end;
1002                         }
1003
1004                 req->req_info->enc.modified = 1;
1005
1006                 if (verbose)
1007                         {
1008                         print_name(bio_err, "new subject=", X509_REQ_get_subject_name(req), nmflag);
1009                         }
1010                 }
1011
1012         if (verify && !x509)
1013                 {
1014                 int tmp=0;
1015
1016                 if (pkey == NULL)
1017                         {
1018                         pkey=X509_REQ_get_pubkey(req);
1019                         tmp=1;
1020                         if (pkey == NULL) goto end;
1021                         }
1022
1023                 i=X509_REQ_verify(req,pkey);
1024                 if (tmp) {
1025                         EVP_PKEY_free(pkey);
1026                         pkey=NULL;
1027                 }
1028
1029                 if (i < 0)
1030                         {
1031                         goto end;
1032                         }
1033                 else if (i == 0)
1034                         {
1035                         BIO_printf(bio_err,"verify failure\n");
1036                         ERR_print_errors(bio_err);
1037                         }
1038                 else /* if (i > 0) */
1039                         BIO_printf(bio_err,"verify OK\n");
1040                 }
1041
1042         if (noout && !text && !modulus && !subject && !pubkey)
1043                 {
1044                 ex=0;
1045                 goto end;
1046                 }
1047
1048         if (outfile == NULL)
1049                 {
1050                 BIO_set_fp(out,stdout,BIO_NOCLOSE);
1051 #ifdef OPENSSL_SYS_VMS
1052                 {
1053                 BIO *tmpbio = BIO_new(BIO_f_linebuffer());
1054                 out = BIO_push(tmpbio, out);
1055                 }
1056 #endif
1057                 }
1058         else
1059                 {
1060                 if ((keyout != NULL) && (strcmp(outfile,keyout) == 0))
1061                         i=(int)BIO_append_filename(out,outfile);
1062                 else
1063                         i=(int)BIO_write_filename(out,outfile);
1064                 if (!i)
1065                         {
1066                         perror(outfile);
1067                         goto end;
1068                         }
1069                 }
1070
1071         if (pubkey)
1072                 {
1073                 EVP_PKEY *tpubkey; 
1074                 tpubkey=X509_REQ_get_pubkey(req);
1075                 if (tpubkey == NULL)
1076                         {
1077                         BIO_printf(bio_err,"Error getting public key\n");
1078                         ERR_print_errors(bio_err);
1079                         goto end;
1080                         }
1081                 PEM_write_bio_PUBKEY(out, tpubkey);
1082                 EVP_PKEY_free(tpubkey);
1083                 }
1084
1085         if (text)
1086                 {
1087                 if (x509)
1088                         X509_print_ex(out, x509ss, nmflag, reqflag);
1089                 else    
1090                         X509_REQ_print_ex(out, req, nmflag, reqflag);
1091                 }
1092
1093         if(subject) 
1094                 {
1095                 if(x509)
1096                         print_name(out, "subject=", X509_get_subject_name(x509ss), nmflag);
1097                 else
1098                         print_name(out, "subject=", X509_REQ_get_subject_name(req), nmflag);
1099                 }
1100
1101         if (modulus)
1102                 {
1103                 EVP_PKEY *tpubkey;
1104
1105                 if (x509)
1106                         tpubkey=X509_get_pubkey(x509ss);
1107                 else
1108                         tpubkey=X509_REQ_get_pubkey(req);
1109                 if (tpubkey == NULL)
1110                         {
1111                         fprintf(stdout,"Modulus=unavailable\n");
1112                         goto end; 
1113                         }
1114                 fprintf(stdout,"Modulus=");
1115 #ifndef OPENSSL_NO_RSA
1116                 if (tpubkey->type == EVP_PKEY_RSA)
1117                         BN_print(out,tpubkey->pkey.rsa->n);
1118                 else
1119 #endif
1120                         fprintf(stdout,"Wrong Algorithm type");
1121                 EVP_PKEY_free(tpubkey);
1122                 fprintf(stdout,"\n");
1123                 }
1124
1125         if (!noout && !x509)
1126                 {
1127                 if      (outformat == FORMAT_ASN1)
1128                         i=i2d_X509_REQ_bio(out,req);
1129                 else if (outformat == FORMAT_PEM) {
1130                         if(newhdr) i=PEM_write_bio_X509_REQ_NEW(out,req);
1131                         else i=PEM_write_bio_X509_REQ(out,req);
1132                 } else {
1133                         BIO_printf(bio_err,"bad output format specified for outfile\n");
1134                         goto end;
1135                         }
1136                 if (!i)
1137                         {
1138                         BIO_printf(bio_err,"unable to write X509 request\n");
1139                         goto end;
1140                         }
1141                 }
1142         if (!noout && x509 && (x509ss != NULL))
1143                 {
1144                 if      (outformat == FORMAT_ASN1)
1145                         i=i2d_X509_bio(out,x509ss);
1146                 else if (outformat == FORMAT_PEM)
1147                         i=PEM_write_bio_X509(out,x509ss);
1148                 else    {
1149                         BIO_printf(bio_err,"bad output format specified for outfile\n");
1150                         goto end;
1151                         }
1152                 if (!i)
1153                         {
1154                         BIO_printf(bio_err,"unable to write X509 certificate\n");
1155                         goto end;
1156                         }
1157                 }
1158         ex=0;
1159 end:
1160 #ifndef MONOLITH
1161         if(to_free)
1162                 OPENSSL_free(to_free);
1163 #endif
1164         if (ex)
1165                 {
1166                 ERR_print_errors(bio_err);
1167                 }
1168         if ((req_conf != NULL) && (req_conf != config)) NCONF_free(req_conf);
1169         BIO_free(in);
1170         BIO_free_all(out);
1171         EVP_PKEY_free(pkey);
1172         X509_REQ_free(req);
1173         X509_free(x509ss);
1174         ASN1_INTEGER_free(serial);
1175         if(passargin && passin) OPENSSL_free(passin);
1176         if(passargout && passout) OPENSSL_free(passout);
1177         OBJ_cleanup();
1178 #ifndef OPENSSL_NO_DSA
1179         if (dsa_params != NULL) DSA_free(dsa_params);
1180 #endif
1181 #ifndef OPENSSL_NO_ECDSA
1182         if (ec_params != NULL) EC_KEY_free(ec_params);
1183 #endif
1184         apps_shutdown();
1185         OPENSSL_EXIT(ex);
1186         }
1187
1188 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1189                         int attribs, unsigned long chtype)
1190         {
1191         int ret=0,i;
1192         char no_prompt = 0;
1193         STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1194         char *tmp, *dn_sect,*attr_sect;
1195
1196         tmp=NCONF_get_string(req_conf,SECTION,PROMPT);
1197         if (tmp == NULL)
1198                 ERR_clear_error();
1199         if((tmp != NULL) && !strcmp(tmp, "no")) no_prompt = 1;
1200
1201         dn_sect=NCONF_get_string(req_conf,SECTION,DISTINGUISHED_NAME);
1202         if (dn_sect == NULL)
1203                 {
1204                 BIO_printf(bio_err,"unable to find '%s' in config\n",
1205                         DISTINGUISHED_NAME);
1206                 goto err;
1207                 }
1208         dn_sk=NCONF_get_section(req_conf,dn_sect);
1209         if (dn_sk == NULL)
1210                 {
1211                 BIO_printf(bio_err,"unable to get '%s' section\n",dn_sect);
1212                 goto err;
1213                 }
1214
1215         attr_sect=NCONF_get_string(req_conf,SECTION,ATTRIBUTES);
1216         if (attr_sect == NULL)
1217                 {
1218                 ERR_clear_error();              
1219                 attr_sk=NULL;
1220                 }
1221         else
1222                 {
1223                 attr_sk=NCONF_get_section(req_conf,attr_sect);
1224                 if (attr_sk == NULL)
1225                         {
1226                         BIO_printf(bio_err,"unable to get '%s' section\n",attr_sect);
1227                         goto err;
1228                         }
1229                 }
1230
1231         /* setup version number */
1232         if (!X509_REQ_set_version(req,0L)) goto err; /* version 1 */
1233
1234         if (no_prompt) 
1235                 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1236         else 
1237                 {
1238                 if (subj)
1239                         i = build_subject(req, subj, chtype, multirdn);
1240                 else
1241                         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs, chtype);
1242                 }
1243         if(!i) goto err;
1244
1245         if (!X509_REQ_set_pubkey(req,pkey)) goto err;
1246
1247         ret=1;
1248 err:
1249         return(ret);
1250         }
1251
1252 /*
1253  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1254  * where characters may be escaped by \
1255  */
1256 static int build_subject(X509_REQ *req, char *subject, unsigned long chtype, int multirdn)
1257         {
1258         X509_NAME *n;
1259
1260         if (!(n = parse_name(subject, chtype, multirdn)))
1261                 return 0;
1262
1263         if (!X509_REQ_set_subject_name(req, n))
1264                 {
1265                 X509_NAME_free(n);
1266                 return 0;
1267                 }
1268         X509_NAME_free(n);
1269         return 1;
1270 }
1271
1272
1273 static int prompt_info(X509_REQ *req,
1274                 STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
1275                 STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect, int attribs,
1276                 unsigned long chtype)
1277         {
1278         int i;
1279         char *p,*q;
1280         char buf[100];
1281         int nid, mval;
1282         long n_min,n_max;
1283         char *type, *value;
1284         const char *def;
1285         CONF_VALUE *v;
1286         X509_NAME *subj;
1287         subj = X509_REQ_get_subject_name(req);
1288
1289         if(!batch)
1290                 {
1291                 BIO_printf(bio_err,"You are about to be asked to enter information that will be incorporated\n");
1292                 BIO_printf(bio_err,"into your certificate request.\n");
1293                 BIO_printf(bio_err,"What you are about to enter is what is called a Distinguished Name or a DN.\n");
1294                 BIO_printf(bio_err,"There are quite a few fields but you can leave some blank\n");
1295                 BIO_printf(bio_err,"For some fields there will be a default value,\n");
1296                 BIO_printf(bio_err,"If you enter '.', the field will be left blank.\n");
1297                 BIO_printf(bio_err,"-----\n");
1298                 }
1299
1300
1301         if (sk_CONF_VALUE_num(dn_sk))
1302                 {
1303                 i= -1;
1304 start:          for (;;)
1305                         {
1306                         i++;
1307                         if (sk_CONF_VALUE_num(dn_sk) <= i) break;
1308
1309                         v=sk_CONF_VALUE_value(dn_sk,i);
1310                         p=q=NULL;
1311                         type=v->name;
1312                         if(!check_end(type,"_min") || !check_end(type,"_max") ||
1313                                 !check_end(type,"_default") ||
1314                                          !check_end(type,"_value")) continue;
1315                         /* Skip past any leading X. X: X, etc to allow for
1316                          * multiple instances 
1317                          */
1318                         for(p = v->name; *p ; p++) 
1319                                 if ((*p == ':') || (*p == ',') ||
1320                                                          (*p == '.')) {
1321                                         p++;
1322                                         if(*p) type = p;
1323                                         break;
1324                                 }
1325                         if (*type == '+')
1326                                 {
1327                                 mval = -1;
1328                                 type++;
1329                                 }
1330                         else
1331                                 mval = 0;
1332                         /* If OBJ not recognised ignore it */
1333                         if ((nid=OBJ_txt2nid(type)) == NID_undef) goto start;
1334                         if (BIO_snprintf(buf,sizeof buf,"%s_default",v->name)
1335                                 >= (int)sizeof(buf))
1336                            {
1337                            BIO_printf(bio_err,"Name '%s' too long\n",v->name);
1338                            return 0;
1339                            }
1340
1341                         if ((def=NCONF_get_string(req_conf,dn_sect,buf)) == NULL)
1342                                 {
1343                                 ERR_clear_error();
1344                                 def="";
1345                                 }
1346                                 
1347                         BIO_snprintf(buf,sizeof buf,"%s_value",v->name);
1348                         if ((value=NCONF_get_string(req_conf,dn_sect,buf)) == NULL)
1349                                 {
1350                                 ERR_clear_error();
1351                                 value=NULL;
1352                                 }
1353
1354                         BIO_snprintf(buf,sizeof buf,"%s_min",v->name);
1355                         if (!NCONF_get_number(req_conf,dn_sect,buf, &n_min))
1356                                 {
1357                                 ERR_clear_error();
1358                                 n_min = -1;
1359                                 }
1360
1361                         BIO_snprintf(buf,sizeof buf,"%s_max",v->name);
1362                         if (!NCONF_get_number(req_conf,dn_sect,buf, &n_max))
1363                                 {
1364                                 ERR_clear_error();
1365                                 n_max = -1;
1366                                 }
1367
1368                         if (!add_DN_object(subj,v->value,def,value,nid,
1369                                 n_min,n_max, chtype, mval))
1370                                 return 0;
1371                         }
1372                 if (X509_NAME_entry_count(subj) == 0)
1373                         {
1374                         BIO_printf(bio_err,"error, no objects specified in config file\n");
1375                         return 0;
1376                         }
1377
1378                 if (attribs)
1379                         {
1380                         if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0) && (!batch))
1381                                 {
1382                                 BIO_printf(bio_err,"\nPlease enter the following 'extra' attributes\n");
1383                                 BIO_printf(bio_err,"to be sent with your certificate request\n");
1384                                 }
1385
1386                         i= -1;
1387 start2:                 for (;;)
1388                                 {
1389                                 i++;
1390                                 if ((attr_sk == NULL) ||
1391                                             (sk_CONF_VALUE_num(attr_sk) <= i))
1392                                         break;
1393
1394                                 v=sk_CONF_VALUE_value(attr_sk,i);
1395                                 type=v->name;
1396                                 if ((nid=OBJ_txt2nid(type)) == NID_undef)
1397                                         goto start2;
1398
1399                                 if (BIO_snprintf(buf,sizeof buf,"%s_default",type)
1400                                         >= (int)sizeof(buf))
1401                                    {
1402                                    BIO_printf(bio_err,"Name '%s' too long\n",v->name);
1403                                    return 0;
1404                                    }
1405
1406                                 if ((def=NCONF_get_string(req_conf,attr_sect,buf))
1407                                         == NULL)
1408                                         {
1409                                         ERR_clear_error();
1410                                         def="";
1411                                         }
1412                                 
1413                                 
1414                                 BIO_snprintf(buf,sizeof buf,"%s_value",type);
1415                                 if ((value=NCONF_get_string(req_conf,attr_sect,buf))
1416                                         == NULL)
1417                                         {
1418                                         ERR_clear_error();
1419                                         value=NULL;
1420                                         }
1421
1422                                 BIO_snprintf(buf,sizeof buf,"%s_min",type);
1423                                 if (!NCONF_get_number(req_conf,attr_sect,buf, &n_min))
1424                                         n_min = -1;
1425
1426                                 BIO_snprintf(buf,sizeof buf,"%s_max",type);
1427                                 if (!NCONF_get_number(req_conf,attr_sect,buf, &n_max))
1428                                         n_max = -1;
1429
1430                                 if (!add_attribute_object(req,
1431                                         v->value,def,value,nid,n_min,n_max, chtype))
1432                                         return 0;
1433                                 }
1434                         }
1435                 }
1436         else
1437                 {
1438                 BIO_printf(bio_err,"No template, please set one up.\n");
1439                 return 0;
1440                 }
1441
1442         return 1;
1443
1444         }
1445
1446 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1447                         STACK_OF(CONF_VALUE) *attr_sk, int attribs, unsigned long chtype)
1448         {
1449         int i;
1450         char *p,*q;
1451         char *type;
1452         CONF_VALUE *v;
1453         X509_NAME *subj;
1454
1455         subj = X509_REQ_get_subject_name(req);
1456
1457         for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++)
1458                 {
1459                 int mval;
1460                 v=sk_CONF_VALUE_value(dn_sk,i);
1461                 p=q=NULL;
1462                 type=v->name;
1463                 /* Skip past any leading X. X: X, etc to allow for
1464                  * multiple instances 
1465                  */
1466                 for(p = v->name; *p ; p++) 
1467 #ifndef CHARSET_EBCDIC
1468                         if ((*p == ':') || (*p == ',') || (*p == '.')) {
1469 #else
1470                         if ((*p == os_toascii[':']) || (*p == os_toascii[',']) || (*p == os_toascii['.'])) {
1471 #endif
1472                                 p++;
1473                                 if(*p) type = p;
1474                                 break;
1475                         }
1476 #ifndef CHARSET_EBCDIC
1477                 if (*p == '+')
1478 #else
1479                 if (*p == os_toascii['+'])
1480 #endif
1481                         {
1482                         p++;
1483                         mval = -1;
1484                         }
1485                 else
1486                         mval = 0;
1487                 if (!X509_NAME_add_entry_by_txt(subj,type, chtype,
1488                                 (unsigned char *) v->value,-1,-1,mval)) return 0;
1489
1490                 }
1491
1492                 if (!X509_NAME_entry_count(subj))
1493                         {
1494                         BIO_printf(bio_err,"error, no objects specified in config file\n");
1495                         return 0;
1496                         }
1497                 if (attribs)
1498                         {
1499                         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++)
1500                                 {
1501                                 v=sk_CONF_VALUE_value(attr_sk,i);
1502                                 if(!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1503                                         (unsigned char *)v->value, -1)) return 0;
1504                                 }
1505                         }
1506         return 1;
1507         }
1508
1509
1510 static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value,
1511              int nid, int n_min, int n_max, unsigned long chtype, int mval)
1512         {
1513         int i,ret=0;
1514         MS_STATIC char buf[1024];
1515 start:
1516         if (!batch) BIO_printf(bio_err,"%s [%s]:",text,def);
1517         (void)BIO_flush(bio_err);
1518         if(value != NULL)
1519                 {
1520                 BUF_strlcpy(buf,value,sizeof buf);
1521                 BUF_strlcat(buf,"\n",sizeof buf);
1522                 BIO_printf(bio_err,"%s\n",value);
1523                 }
1524         else
1525                 {
1526                 buf[0]='\0';
1527                 if (!batch)
1528                         {
1529                         fgets(buf,sizeof buf,stdin);
1530                         }
1531                 else
1532                         {
1533                         buf[0] = '\n';
1534                         buf[1] = '\0';
1535                         }
1536                 }
1537
1538         if (buf[0] == '\0') return(0);
1539         else if (buf[0] == '\n')
1540                 {
1541                 if ((def == NULL) || (def[0] == '\0'))
1542                         return(1);
1543                 BUF_strlcpy(buf,def,sizeof buf);
1544                 BUF_strlcat(buf,"\n",sizeof buf);
1545                 }
1546         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1547
1548         i=strlen(buf);
1549         if (buf[i-1] != '\n')
1550                 {
1551                 BIO_printf(bio_err,"weird input :-(\n");
1552                 return(0);
1553                 }
1554         buf[--i]='\0';
1555 #ifdef CHARSET_EBCDIC
1556         ebcdic2ascii(buf, buf, i);
1557 #endif
1558         if(!req_check_len(i, n_min, n_max)) goto start;
1559         if (!X509_NAME_add_entry_by_NID(n,nid, chtype,
1560                                 (unsigned char *) buf, -1,-1,mval)) goto err;
1561         ret=1;
1562 err:
1563         return(ret);
1564         }
1565
1566 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1567                                 char *value, int nid, int n_min,
1568                                 int n_max, unsigned long chtype)
1569         {
1570         int i;
1571         static char buf[1024];
1572
1573 start:
1574         if (!batch) BIO_printf(bio_err,"%s [%s]:",text,def);
1575         (void)BIO_flush(bio_err);
1576         if (value != NULL)
1577                 {
1578                 BUF_strlcpy(buf,value,sizeof buf);
1579                 BUF_strlcat(buf,"\n",sizeof buf);
1580                 BIO_printf(bio_err,"%s\n",value);
1581                 }
1582         else
1583                 {
1584                 buf[0]='\0';
1585                 if (!batch)
1586                         {
1587                         fgets(buf,sizeof buf,stdin);
1588                         }
1589                 else
1590                         {
1591                         buf[0] = '\n';
1592                         buf[1] = '\0';
1593                         }
1594                 }
1595
1596         if (buf[0] == '\0') return(0);
1597         else if (buf[0] == '\n')
1598                 {
1599                 if ((def == NULL) || (def[0] == '\0'))
1600                         return(1);
1601                 BUF_strlcpy(buf,def,sizeof buf);
1602                 BUF_strlcat(buf,"\n",sizeof buf);
1603                 }
1604         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1605
1606         i=strlen(buf);
1607         if (buf[i-1] != '\n')
1608                 {
1609                 BIO_printf(bio_err,"weird input :-(\n");
1610                 return(0);
1611                 }
1612         buf[--i]='\0';
1613 #ifdef CHARSET_EBCDIC
1614         ebcdic2ascii(buf, buf, i);
1615 #endif
1616         if(!req_check_len(i, n_min, n_max)) goto start;
1617
1618         if(!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1619                                         (unsigned char *)buf, -1)) {
1620                 BIO_printf(bio_err, "Error adding attribute\n");
1621                 ERR_print_errors(bio_err);
1622                 goto err;
1623         }
1624
1625         return(1);
1626 err:
1627         return(0);
1628         }
1629
1630 #ifndef OPENSSL_NO_RSA
1631 static int MS_CALLBACK req_cb(int p, int n, BN_GENCB *cb)
1632         {
1633         char c='*';
1634
1635         if (p == 0) c='.';
1636         if (p == 1) c='+';
1637         if (p == 2) c='*';
1638         if (p == 3) c='\n';
1639         BIO_write(cb->arg,&c,1);
1640         (void)BIO_flush(cb->arg);
1641 #ifdef LINT
1642         p=n;
1643 #endif
1644         return 1;
1645         }
1646 #endif
1647
1648 static int req_check_len(int len, int n_min, int n_max)
1649         {
1650         if ((n_min > 0) && (len < n_min))
1651                 {
1652                 BIO_printf(bio_err,"string is too short, it needs to be at least %d bytes long\n",n_min);
1653                 return(0);
1654                 }
1655         if ((n_max >= 0) && (len > n_max))
1656                 {
1657                 BIO_printf(bio_err,"string is too long, it needs to be less than  %d bytes long\n",n_max);
1658                 return(0);
1659                 }
1660         return(1);
1661         }
1662
1663 /* Check if the end of a string matches 'end' */
1664 static int check_end(const char *str, const char *end)
1665 {
1666         int elen, slen; 
1667         const char *tmp;
1668         elen = strlen(end);
1669         slen = strlen(str);
1670         if(elen > slen) return 1;
1671         tmp = str + slen - elen;
1672         return strcmp(tmp, end);
1673 }