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