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