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