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