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