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