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