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