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