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