Cover all DSA setups when running tests
[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                         if(!rsa || !RSA_generate_key_ex(rsa, newkey, 0x10001, &cb) ||
752                                         !EVP_PKEY_assign_RSA(pkey, rsa))
753                                 {
754                                 if(rsa) RSA_free(rsa);
755                                 goto end;
756                                 }
757                         }
758                 else
759 #endif
760 #ifndef OPENSSL_NO_DSA
761                         if (pkey_type == TYPE_DSA)
762                         {
763                         if (!DSA_generate_key(dsa_params)) goto end;
764                         if (!EVP_PKEY_assign_DSA(pkey,dsa_params)) goto end;
765                         dsa_params=NULL;
766                         }
767 #endif
768 #ifndef OPENSSL_NO_ECDSA
769                         if (pkey_type == TYPE_EC)
770                         {
771                         if (!EC_KEY_generate_key(ec_params)) goto end;
772                         if (!EVP_PKEY_assign_EC_KEY(pkey, ec_params)) 
773                                 goto end;
774                         ec_params = NULL;
775                         }
776 #endif
777
778                 app_RAND_write_file(randfile, bio_err);
779
780                 if (pkey == NULL) goto end;
781
782                 if (keyout == NULL)
783                         {
784                         keyout=NCONF_get_string(req_conf,SECTION,KEYFILE);
785                         if (keyout == NULL)
786                                 ERR_clear_error();
787                         }
788                 
789                 if (keyout == NULL)
790                         {
791                         BIO_printf(bio_err,"writing new private key to stdout\n");
792                         BIO_set_fp(out,stdout,BIO_NOCLOSE);
793 #ifdef OPENSSL_SYS_VMS
794                         {
795                         BIO *tmpbio = BIO_new(BIO_f_linebuffer());
796                         out = BIO_push(tmpbio, out);
797                         }
798 #endif
799                         }
800                 else
801                         {
802                         BIO_printf(bio_err,"writing new private key to '%s'\n",keyout);
803                         if (BIO_write_filename(out,keyout) <= 0)
804                                 {
805                                 perror(keyout);
806                                 goto end;
807                                 }
808                         }
809
810                 p=NCONF_get_string(req_conf,SECTION,"encrypt_rsa_key");
811                 if (p == NULL)
812                         {
813                         ERR_clear_error();
814                         p=NCONF_get_string(req_conf,SECTION,"encrypt_key");
815                         if (p == NULL)
816                                 ERR_clear_error();
817                         }
818                 if ((p != NULL) && (strcmp(p,"no") == 0))
819                         cipher=NULL;
820                 if (nodes) cipher=NULL;
821                 
822                 i=0;
823 loop:
824                 if (!PEM_write_bio_PrivateKey(out,pkey,cipher,
825                         NULL,0,NULL,passout))
826                         {
827                         if ((ERR_GET_REASON(ERR_peek_error()) ==
828                                 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3))
829                                 {
830                                 ERR_clear_error();
831                                 i++;
832                                 goto loop;
833                                 }
834                         goto end;
835                         }
836                 BIO_printf(bio_err,"-----\n");
837                 }
838
839         if (!newreq)
840                 {
841                 /* Since we are using a pre-existing certificate
842                  * request, the kludge 'format' info should not be
843                  * changed. */
844                 kludge= -1;
845                 if (infile == NULL)
846                         BIO_set_fp(in,stdin,BIO_NOCLOSE);
847                 else
848                         {
849                         if (BIO_read_filename(in,infile) <= 0)
850                                 {
851                                 perror(infile);
852                                 goto end;
853                                 }
854                         }
855
856                 if      (informat == FORMAT_ASN1)
857                         req=d2i_X509_REQ_bio(in,NULL);
858                 else if (informat == FORMAT_PEM)
859                         req=PEM_read_bio_X509_REQ(in,NULL,NULL,NULL);
860                 else
861                         {
862                         BIO_printf(bio_err,"bad input format specified for X509 request\n");
863                         goto end;
864                         }
865                 if (req == NULL)
866                         {
867                         BIO_printf(bio_err,"unable to load X509 request\n");
868                         goto end;
869                         }
870                 }
871
872         if (newreq || x509)
873                 {
874                 if (pkey == NULL)
875                         {
876                         BIO_printf(bio_err,"you need to specify a private key\n");
877                         goto end;
878                         }
879 #ifndef OPENSSL_NO_DSA
880                 if (pkey->type == EVP_PKEY_DSA)
881                         digest=EVP_dss1();
882 #endif
883 #ifndef OPENSSL_NO_ECDSA
884                 if (pkey->type == EVP_PKEY_EC)
885                         digest=EVP_ecdsa();
886 #endif
887                 if (req == NULL)
888                         {
889                         req=X509_REQ_new();
890                         if (req == NULL)
891                                 {
892                                 goto end;
893                                 }
894
895                         i=make_REQ(req,pkey,subj,multirdn,!x509, chtype);
896                         subj=NULL; /* done processing '-subj' option */
897                         if ((kludge > 0) && !sk_X509_ATTRIBUTE_num(req->req_info->attributes))
898                                 {
899                                 sk_X509_ATTRIBUTE_free(req->req_info->attributes);
900                                 req->req_info->attributes = NULL;
901                                 }
902                         if (!i)
903                                 {
904                                 BIO_printf(bio_err,"problems making Certificate Request\n");
905                                 goto end;
906                                 }
907                         }
908                 if (x509)
909                         {
910                         EVP_PKEY *tmppkey;
911                         X509V3_CTX ext_ctx;
912                         if ((x509ss=X509_new()) == NULL) goto end;
913
914                         /* Set version to V3 */
915                         if(extensions && !X509_set_version(x509ss, 2)) goto end;
916                         if (serial)
917                                 {
918                                 if (!X509_set_serialNumber(x509ss, serial)) goto end;
919                                 }
920                         else
921                                 {
922                                 if (!ASN1_INTEGER_set(X509_get_serialNumber(x509ss),0L)) goto end;
923                                 }
924
925                         if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req))) goto end;
926                         if (!X509_gmtime_adj(X509_get_notBefore(x509ss),0)) goto end;
927                         if (!X509_gmtime_adj(X509_get_notAfter(x509ss), (long)60*60*24*days)) goto end;
928                         if (!X509_set_subject_name(x509ss, X509_REQ_get_subject_name(req))) goto end;
929                         tmppkey = X509_REQ_get_pubkey(req);
930                         if (!tmppkey || !X509_set_pubkey(x509ss,tmppkey)) goto end;
931                         EVP_PKEY_free(tmppkey);
932
933                         /* Set up V3 context struct */
934
935                         X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
936                         X509V3_set_nconf(&ext_ctx, req_conf);
937
938                         /* Add extensions */
939                         if(extensions && !X509V3_EXT_add_nconf(req_conf, 
940                                         &ext_ctx, extensions, x509ss))
941                                 {
942                                 BIO_printf(bio_err,
943                                         "Error Loading extension section %s\n",
944                                         extensions);
945                                 goto end;
946                                 }
947                         
948                         if (!(i=X509_sign(x509ss,pkey,digest)))
949                                 goto end;
950                         }
951                 else
952                         {
953                         X509V3_CTX ext_ctx;
954
955                         /* Set up V3 context struct */
956
957                         X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
958                         X509V3_set_nconf(&ext_ctx, req_conf);
959
960                         /* Add extensions */
961                         if(req_exts && !X509V3_EXT_REQ_add_nconf(req_conf, 
962                                         &ext_ctx, req_exts, req))
963                                 {
964                                 BIO_printf(bio_err,
965                                         "Error Loading extension section %s\n",
966                                         req_exts);
967                                 goto end;
968                                 }
969                         if (!(i=X509_REQ_sign(req,pkey,digest)))
970                                 goto end;
971                         }
972                 }
973
974         if (subj && x509)
975                 {
976                 BIO_printf(bio_err, "Cannot modifiy certificate subject\n");
977                 goto end;
978                 }
979
980         if (subj && !x509)
981                 {
982                 if (verbose)
983                         {
984                         BIO_printf(bio_err, "Modifying Request's Subject\n");
985                         print_name(bio_err, "old subject=", X509_REQ_get_subject_name(req), nmflag);
986                         }
987
988                 if (build_subject(req, subj, chtype, multirdn) == 0)
989                         {
990                         BIO_printf(bio_err, "ERROR: cannot modify subject\n");
991                         ex=1;
992                         goto end;
993                         }
994
995                 req->req_info->enc.modified = 1;
996
997                 if (verbose)
998                         {
999                         print_name(bio_err, "new subject=", X509_REQ_get_subject_name(req), nmflag);
1000                         }
1001                 }
1002
1003         if (verify && !x509)
1004                 {
1005                 int tmp=0;
1006
1007                 if (pkey == NULL)
1008                         {
1009                         pkey=X509_REQ_get_pubkey(req);
1010                         tmp=1;
1011                         if (pkey == NULL) goto end;
1012                         }
1013
1014                 i=X509_REQ_verify(req,pkey);
1015                 if (tmp) {
1016                         EVP_PKEY_free(pkey);
1017                         pkey=NULL;
1018                 }
1019
1020                 if (i < 0)
1021                         {
1022                         goto end;
1023                         }
1024                 else if (i == 0)
1025                         {
1026                         BIO_printf(bio_err,"verify failure\n");
1027                         ERR_print_errors(bio_err);
1028                         }
1029                 else /* if (i > 0) */
1030                         BIO_printf(bio_err,"verify OK\n");
1031                 }
1032
1033         if (noout && !text && !modulus && !subject && !pubkey)
1034                 {
1035                 ex=0;
1036                 goto end;
1037                 }
1038
1039         if (outfile == NULL)
1040                 {
1041                 BIO_set_fp(out,stdout,BIO_NOCLOSE);
1042 #ifdef OPENSSL_SYS_VMS
1043                 {
1044                 BIO *tmpbio = BIO_new(BIO_f_linebuffer());
1045                 out = BIO_push(tmpbio, out);
1046                 }
1047 #endif
1048                 }
1049         else
1050                 {
1051                 if ((keyout != NULL) && (strcmp(outfile,keyout) == 0))
1052                         i=(int)BIO_append_filename(out,outfile);
1053                 else
1054                         i=(int)BIO_write_filename(out,outfile);
1055                 if (!i)
1056                         {
1057                         perror(outfile);
1058                         goto end;
1059                         }
1060                 }
1061
1062         if (pubkey)
1063                 {
1064                 EVP_PKEY *tpubkey; 
1065                 tpubkey=X509_REQ_get_pubkey(req);
1066                 if (tpubkey == NULL)
1067                         {
1068                         BIO_printf(bio_err,"Error getting public key\n");
1069                         ERR_print_errors(bio_err);
1070                         goto end;
1071                         }
1072                 PEM_write_bio_PUBKEY(out, tpubkey);
1073                 EVP_PKEY_free(tpubkey);
1074                 }
1075
1076         if (text)
1077                 {
1078                 if (x509)
1079                         X509_print_ex(out, x509ss, nmflag, reqflag);
1080                 else    
1081                         X509_REQ_print_ex(out, req, nmflag, reqflag);
1082                 }
1083
1084         if(subject) 
1085                 {
1086                 if(x509)
1087                         print_name(out, "subject=", X509_get_subject_name(x509ss), nmflag);
1088                 else
1089                         print_name(out, "subject=", X509_REQ_get_subject_name(req), nmflag);
1090                 }
1091
1092         if (modulus)
1093                 {
1094                 EVP_PKEY *tpubkey;
1095
1096                 if (x509)
1097                         tpubkey=X509_get_pubkey(x509ss);
1098                 else
1099                         tpubkey=X509_REQ_get_pubkey(req);
1100                 if (tpubkey == NULL)
1101                         {
1102                         fprintf(stdout,"Modulus=unavailable\n");
1103                         goto end; 
1104                         }
1105                 fprintf(stdout,"Modulus=");
1106 #ifndef OPENSSL_NO_RSA
1107                 if (tpubkey->type == EVP_PKEY_RSA)
1108                         BN_print(out,tpubkey->pkey.rsa->n);
1109                 else
1110 #endif
1111                         fprintf(stdout,"Wrong Algorithm type");
1112                 EVP_PKEY_free(tpubkey);
1113                 fprintf(stdout,"\n");
1114                 }
1115
1116         if (!noout && !x509)
1117                 {
1118                 if      (outformat == FORMAT_ASN1)
1119                         i=i2d_X509_REQ_bio(out,req);
1120                 else if (outformat == FORMAT_PEM) {
1121                         if(newhdr) i=PEM_write_bio_X509_REQ_NEW(out,req);
1122                         else i=PEM_write_bio_X509_REQ(out,req);
1123                 } else {
1124                         BIO_printf(bio_err,"bad output format specified for outfile\n");
1125                         goto end;
1126                         }
1127                 if (!i)
1128                         {
1129                         BIO_printf(bio_err,"unable to write X509 request\n");
1130                         goto end;
1131                         }
1132                 }
1133         if (!noout && x509 && (x509ss != NULL))
1134                 {
1135                 if      (outformat == FORMAT_ASN1)
1136                         i=i2d_X509_bio(out,x509ss);
1137                 else if (outformat == FORMAT_PEM)
1138                         i=PEM_write_bio_X509(out,x509ss);
1139                 else    {
1140                         BIO_printf(bio_err,"bad output format specified for outfile\n");
1141                         goto end;
1142                         }
1143                 if (!i)
1144                         {
1145                         BIO_printf(bio_err,"unable to write X509 certificate\n");
1146                         goto end;
1147                         }
1148                 }
1149         ex=0;
1150 end:
1151 #ifndef MONOLITH
1152         if(to_free)
1153                 OPENSSL_free(to_free);
1154 #endif
1155         if (ex)
1156                 {
1157                 ERR_print_errors(bio_err);
1158                 }
1159         if ((req_conf != NULL) && (req_conf != config)) NCONF_free(req_conf);
1160         BIO_free(in);
1161         BIO_free_all(out);
1162         EVP_PKEY_free(pkey);
1163         X509_REQ_free(req);
1164         X509_free(x509ss);
1165         ASN1_INTEGER_free(serial);
1166         if(passargin && passin) OPENSSL_free(passin);
1167         if(passargout && passout) OPENSSL_free(passout);
1168         OBJ_cleanup();
1169 #ifndef OPENSSL_NO_DSA
1170         if (dsa_params != NULL) DSA_free(dsa_params);
1171 #endif
1172 #ifndef OPENSSL_NO_ECDSA
1173         if (ec_params != NULL) EC_KEY_free(ec_params);
1174 #endif
1175         apps_shutdown();
1176         OPENSSL_EXIT(ex);
1177         }
1178
1179 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1180                         int attribs, unsigned long chtype)
1181         {
1182         int ret=0,i;
1183         char no_prompt = 0;
1184         STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1185         char *tmp, *dn_sect,*attr_sect;
1186
1187         tmp=NCONF_get_string(req_conf,SECTION,PROMPT);
1188         if (tmp == NULL)
1189                 ERR_clear_error();
1190         if((tmp != NULL) && !strcmp(tmp, "no")) no_prompt = 1;
1191
1192         dn_sect=NCONF_get_string(req_conf,SECTION,DISTINGUISHED_NAME);
1193         if (dn_sect == NULL)
1194                 {
1195                 BIO_printf(bio_err,"unable to find '%s' in config\n",
1196                         DISTINGUISHED_NAME);
1197                 goto err;
1198                 }
1199         dn_sk=NCONF_get_section(req_conf,dn_sect);
1200         if (dn_sk == NULL)
1201                 {
1202                 BIO_printf(bio_err,"unable to get '%s' section\n",dn_sect);
1203                 goto err;
1204                 }
1205
1206         attr_sect=NCONF_get_string(req_conf,SECTION,ATTRIBUTES);
1207         if (attr_sect == NULL)
1208                 {
1209                 ERR_clear_error();              
1210                 attr_sk=NULL;
1211                 }
1212         else
1213                 {
1214                 attr_sk=NCONF_get_section(req_conf,attr_sect);
1215                 if (attr_sk == NULL)
1216                         {
1217                         BIO_printf(bio_err,"unable to get '%s' section\n",attr_sect);
1218                         goto err;
1219                         }
1220                 }
1221
1222         /* setup version number */
1223         if (!X509_REQ_set_version(req,0L)) goto err; /* version 1 */
1224
1225         if (no_prompt) 
1226                 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1227         else 
1228                 {
1229                 if (subj)
1230                         i = build_subject(req, subj, chtype, multirdn);
1231                 else
1232                         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs, chtype);
1233                 }
1234         if(!i) goto err;
1235
1236         if (!X509_REQ_set_pubkey(req,pkey)) goto err;
1237
1238         ret=1;
1239 err:
1240         return(ret);
1241         }
1242
1243 /*
1244  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1245  * where characters may be escaped by \
1246  */
1247 static int build_subject(X509_REQ *req, char *subject, unsigned long chtype, int multirdn)
1248         {
1249         X509_NAME *n;
1250
1251         if (!(n = parse_name(subject, chtype, multirdn)))
1252                 return 0;
1253
1254         if (!X509_REQ_set_subject_name(req, n))
1255                 {
1256                 X509_NAME_free(n);
1257                 return 0;
1258                 }
1259         X509_NAME_free(n);
1260         return 1;
1261 }
1262
1263
1264 static int prompt_info(X509_REQ *req,
1265                 STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
1266                 STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect, int attribs,
1267                 unsigned long chtype)
1268         {
1269         int i;
1270         char *p,*q;
1271         char buf[100];
1272         int nid, mval;
1273         long n_min,n_max;
1274         char *type,*def,*value;
1275         CONF_VALUE *v;
1276         X509_NAME *subj;
1277         subj = X509_REQ_get_subject_name(req);
1278
1279         if(!batch)
1280                 {
1281                 BIO_printf(bio_err,"You are about to be asked to enter information that will be incorporated\n");
1282                 BIO_printf(bio_err,"into your certificate request.\n");
1283                 BIO_printf(bio_err,"What you are about to enter is what is called a Distinguished Name or a DN.\n");
1284                 BIO_printf(bio_err,"There are quite a few fields but you can leave some blank\n");
1285                 BIO_printf(bio_err,"For some fields there will be a default value,\n");
1286                 BIO_printf(bio_err,"If you enter '.', the field will be left blank.\n");
1287                 BIO_printf(bio_err,"-----\n");
1288                 }
1289
1290
1291         if (sk_CONF_VALUE_num(dn_sk))
1292                 {
1293                 i= -1;
1294 start:          for (;;)
1295                         {
1296                         i++;
1297                         if (sk_CONF_VALUE_num(dn_sk) <= i) break;
1298
1299                         v=sk_CONF_VALUE_value(dn_sk,i);
1300                         p=q=NULL;
1301                         type=v->name;
1302                         if(!check_end(type,"_min") || !check_end(type,"_max") ||
1303                                 !check_end(type,"_default") ||
1304                                          !check_end(type,"_value")) continue;
1305                         /* Skip past any leading X. X: X, etc to allow for
1306                          * multiple instances 
1307                          */
1308                         for(p = v->name; *p ; p++) 
1309                                 if ((*p == ':') || (*p == ',') ||
1310                                                          (*p == '.')) {
1311                                         p++;
1312                                         if(*p) type = p;
1313                                         break;
1314                                 }
1315                         if (*type == '+')
1316                                 {
1317                                 mval = -1;
1318                                 type++;
1319                                 }
1320                         else
1321                                 mval = 0;
1322                         /* If OBJ not recognised ignore it */
1323                         if ((nid=OBJ_txt2nid(type)) == NID_undef) goto start;
1324                         if (BIO_snprintf(buf,sizeof buf,"%s_default",v->name)
1325                                 >= sizeof buf)
1326                            {
1327                            BIO_printf(bio_err,"Name '%s' too long\n",v->name);
1328                            return 0;
1329                            }
1330
1331                         if ((def=NCONF_get_string(req_conf,dn_sect,buf)) == NULL)
1332                                 {
1333                                 ERR_clear_error();
1334                                 def="";
1335                                 }
1336                                 
1337                         BIO_snprintf(buf,sizeof buf,"%s_value",v->name);
1338                         if ((value=NCONF_get_string(req_conf,dn_sect,buf)) == NULL)
1339                                 {
1340                                 ERR_clear_error();
1341                                 value=NULL;
1342                                 }
1343
1344                         BIO_snprintf(buf,sizeof buf,"%s_min",v->name);
1345                         if (!NCONF_get_number(req_conf,dn_sect,buf, &n_min))
1346                                 {
1347                                 ERR_clear_error();
1348                                 n_min = -1;
1349                                 }
1350
1351                         BIO_snprintf(buf,sizeof buf,"%s_max",v->name);
1352                         if (!NCONF_get_number(req_conf,dn_sect,buf, &n_max))
1353                                 {
1354                                 ERR_clear_error();
1355                                 n_max = -1;
1356                                 }
1357
1358                         if (!add_DN_object(subj,v->value,def,value,nid,
1359                                 n_min,n_max, chtype, mval))
1360                                 return 0;
1361                         }
1362                 if (X509_NAME_entry_count(subj) == 0)
1363                         {
1364                         BIO_printf(bio_err,"error, no objects specified in config file\n");
1365                         return 0;
1366                         }
1367
1368                 if (attribs)
1369                         {
1370                         if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0) && (!batch))
1371                                 {
1372                                 BIO_printf(bio_err,"\nPlease enter the following 'extra' attributes\n");
1373                                 BIO_printf(bio_err,"to be sent with your certificate request\n");
1374                                 }
1375
1376                         i= -1;
1377 start2:                 for (;;)
1378                                 {
1379                                 i++;
1380                                 if ((attr_sk == NULL) ||
1381                                             (sk_CONF_VALUE_num(attr_sk) <= i))
1382                                         break;
1383
1384                                 v=sk_CONF_VALUE_value(attr_sk,i);
1385                                 type=v->name;
1386                                 if ((nid=OBJ_txt2nid(type)) == NID_undef)
1387                                         goto start2;
1388
1389                                 if (BIO_snprintf(buf,sizeof buf,"%s_default",type)
1390                                         >= sizeof buf)
1391                                    {
1392                                    BIO_printf(bio_err,"Name '%s' too long\n",v->name);
1393                                    return 0;
1394                                    }
1395
1396                                 if ((def=NCONF_get_string(req_conf,attr_sect,buf))
1397                                         == NULL)
1398                                         {
1399                                         ERR_clear_error();
1400                                         def="";
1401                                         }
1402                                 
1403                                 
1404                                 BIO_snprintf(buf,sizeof buf,"%s_value",type);
1405                                 if ((value=NCONF_get_string(req_conf,attr_sect,buf))
1406                                         == NULL)
1407                                         {
1408                                         ERR_clear_error();
1409                                         value=NULL;
1410                                         }
1411
1412                                 BIO_snprintf(buf,sizeof buf,"%s_min",type);
1413                                 if (!NCONF_get_number(req_conf,attr_sect,buf, &n_min))
1414                                         n_min = -1;
1415
1416                                 BIO_snprintf(buf,sizeof buf,"%s_max",type);
1417                                 if (!NCONF_get_number(req_conf,attr_sect,buf, &n_max))
1418                                         n_max = -1;
1419
1420                                 if (!add_attribute_object(req,
1421                                         v->value,def,value,nid,n_min,n_max, chtype))
1422                                         return 0;
1423                                 }
1424                         }
1425                 }
1426         else
1427                 {
1428                 BIO_printf(bio_err,"No template, please set one up.\n");
1429                 return 0;
1430                 }
1431
1432         return 1;
1433
1434         }
1435
1436 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1437                         STACK_OF(CONF_VALUE) *attr_sk, int attribs, unsigned long chtype)
1438         {
1439         int i;
1440         char *p,*q;
1441         char *type;
1442         CONF_VALUE *v;
1443         X509_NAME *subj;
1444
1445         subj = X509_REQ_get_subject_name(req);
1446
1447         for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++)
1448                 {
1449                 int mval;
1450                 v=sk_CONF_VALUE_value(dn_sk,i);
1451                 p=q=NULL;
1452                 type=v->name;
1453                 /* Skip past any leading X. X: X, etc to allow for
1454                  * multiple instances 
1455                  */
1456                 for(p = v->name; *p ; p++) 
1457 #ifndef CHARSET_EBCDIC
1458                         if ((*p == ':') || (*p == ',') || (*p == '.')) {
1459 #else
1460                         if ((*p == os_toascii[':']) || (*p == os_toascii[',']) || (*p == os_toascii['.'])) {
1461 #endif
1462                                 p++;
1463                                 if(*p) type = p;
1464                                 break;
1465                         }
1466 #ifndef CHARSET_EBCDIC
1467                 if (*p == '+')
1468 #else
1469                 if (*p == os_toascii['+'])
1470 #endif
1471                         {
1472                         p++;
1473                         mval = -1;
1474                         }
1475                 else
1476                         mval = 0;
1477                 if (!X509_NAME_add_entry_by_txt(subj,type, chtype,
1478                                 (unsigned char *) v->value,-1,-1,mval)) return 0;
1479
1480                 }
1481
1482                 if (!X509_NAME_entry_count(subj))
1483                         {
1484                         BIO_printf(bio_err,"error, no objects specified in config file\n");
1485                         return 0;
1486                         }
1487                 if (attribs)
1488                         {
1489                         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++)
1490                                 {
1491                                 v=sk_CONF_VALUE_value(attr_sk,i);
1492                                 if(!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1493                                         (unsigned char *)v->value, -1)) return 0;
1494                                 }
1495                         }
1496         return 1;
1497         }
1498
1499
1500 static int add_DN_object(X509_NAME *n, char *text, char *def, char *value,
1501              int nid, int n_min, int n_max, unsigned long chtype, int mval)
1502         {
1503         int i,ret=0;
1504         MS_STATIC char buf[1024];
1505 start:
1506         if (!batch) BIO_printf(bio_err,"%s [%s]:",text,def);
1507         (void)BIO_flush(bio_err);
1508         if(value != NULL)
1509                 {
1510                 BUF_strlcpy(buf,value,sizeof buf);
1511                 BUF_strlcat(buf,"\n",sizeof buf);
1512                 BIO_printf(bio_err,"%s\n",value);
1513                 }
1514         else
1515                 {
1516                 buf[0]='\0';
1517                 if (!batch)
1518                         {
1519                         fgets(buf,sizeof buf,stdin);
1520                         }
1521                 else
1522                         {
1523                         buf[0] = '\n';
1524                         buf[1] = '\0';
1525                         }
1526                 }
1527
1528         if (buf[0] == '\0') return(0);
1529         else if (buf[0] == '\n')
1530                 {
1531                 if ((def == NULL) || (def[0] == '\0'))
1532                         return(1);
1533                 BUF_strlcpy(buf,def,sizeof buf);
1534                 BUF_strlcat(buf,"\n",sizeof buf);
1535                 }
1536         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1537
1538         i=strlen(buf);
1539         if (buf[i-1] != '\n')
1540                 {
1541                 BIO_printf(bio_err,"weird input :-(\n");
1542                 return(0);
1543                 }
1544         buf[--i]='\0';
1545 #ifdef CHARSET_EBCDIC
1546         ebcdic2ascii(buf, buf, i);
1547 #endif
1548         if(!req_check_len(i, n_min, n_max)) goto start;
1549         if (!X509_NAME_add_entry_by_NID(n,nid, chtype,
1550                                 (unsigned char *) buf, -1,-1,mval)) goto err;
1551         ret=1;
1552 err:
1553         return(ret);
1554         }
1555
1556 static int add_attribute_object(X509_REQ *req, char *text,
1557                                 char *def, char *value, int nid, int n_min,
1558                                 int n_max, unsigned long chtype)
1559         {
1560         int i;
1561         static char buf[1024];
1562
1563 start:
1564         if (!batch) BIO_printf(bio_err,"%s [%s]:",text,def);
1565         (void)BIO_flush(bio_err);
1566         if (value != NULL)
1567                 {
1568                 BUF_strlcpy(buf,value,sizeof buf);
1569                 BUF_strlcat(buf,"\n",sizeof buf);
1570                 BIO_printf(bio_err,"%s\n",value);
1571                 }
1572         else
1573                 {
1574                 buf[0]='\0';
1575                 if (!batch)
1576                         {
1577                         fgets(buf,sizeof buf,stdin);
1578                         }
1579                 else
1580                         {
1581                         buf[0] = '\n';
1582                         buf[1] = '\0';
1583                         }
1584                 }
1585
1586         if (buf[0] == '\0') return(0);
1587         else if (buf[0] == '\n')
1588                 {
1589                 if ((def == NULL) || (def[0] == '\0'))
1590                         return(1);
1591                 BUF_strlcpy(buf,def,sizeof buf);
1592                 BUF_strlcat(buf,"\n",sizeof buf);
1593                 }
1594         else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1595
1596         i=strlen(buf);
1597         if (buf[i-1] != '\n')
1598                 {
1599                 BIO_printf(bio_err,"weird input :-(\n");
1600                 return(0);
1601                 }
1602         buf[--i]='\0';
1603 #ifdef CHARSET_EBCDIC
1604         ebcdic2ascii(buf, buf, i);
1605 #endif
1606         if(!req_check_len(i, n_min, n_max)) goto start;
1607
1608         if(!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1609                                         (unsigned char *)buf, -1)) {
1610                 BIO_printf(bio_err, "Error adding attribute\n");
1611                 ERR_print_errors(bio_err);
1612                 goto err;
1613         }
1614
1615         return(1);
1616 err:
1617         return(0);
1618         }
1619
1620 #ifndef OPENSSL_NO_RSA
1621 static int MS_CALLBACK req_cb(int p, int n, BN_GENCB *cb)
1622         {
1623         char c='*';
1624
1625         if (p == 0) c='.';
1626         if (p == 1) c='+';
1627         if (p == 2) c='*';
1628         if (p == 3) c='\n';
1629         BIO_write(cb->arg,&c,1);
1630         (void)BIO_flush(cb->arg);
1631 #ifdef LINT
1632         p=n;
1633 #endif
1634         return 1;
1635         }
1636 #endif
1637
1638 static int req_check_len(int len, int n_min, int n_max)
1639         {
1640         if ((n_min > 0) && (len < n_min))
1641                 {
1642                 BIO_printf(bio_err,"string is too short, it needs to be at least %d bytes long\n",n_min);
1643                 return(0);
1644                 }
1645         if ((n_max >= 0) && (len > n_max))
1646                 {
1647                 BIO_printf(bio_err,"string is too long, it needs to be less than  %d bytes long\n",n_max);
1648                 return(0);
1649                 }
1650         return(1);
1651         }
1652
1653 /* Check if the end of a string matches 'end' */
1654 static int check_end(char *str, char *end)
1655 {
1656         int elen, slen; 
1657         char *tmp;
1658         elen = strlen(end);
1659         slen = strlen(str);
1660         if(elen > slen) return 1;
1661         tmp = str + slen - elen;
1662         return strcmp(tmp, end);
1663 }