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