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