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