4900a922912cdfbf7ff61a9f37eef00662f55321
[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      2048
93 #define MIN_KEY_LENGTH          512
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_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
129     OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_EXTENSIONS,
130     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, 's', "Private key to use"},
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', "Output file pass phrase source"},
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', "Public key options as opt:value"},
151     {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
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, '-', "Verbose output"},
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     {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
167     {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
168     {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
169     {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
170      "Enable support for multivalued RDNs"},
171     {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
172     {"set_serial", OPT_SET_SERIAL, 'p', "Serial number to use"},
173     {"extensions", OPT_EXTENSIONS, 's',
174      "Cert extension section (override value in config file)"},
175     {"reqexts", OPT_REQEXTS, 's',
176      "Request extension section (override value in config file)"},
177     {"", OPT_MD, '-', "Any supported digest"},
178 #ifndef OPENSSL_NO_ENGINE
179     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
180     {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
181      "Specify engine to be used for key generation operations"},
182 #endif
183     {NULL}
184 };
185
186 int req_main(int argc, char **argv)
187 {
188     ASN1_INTEGER *serial = NULL;
189     BIO *in = NULL, *out = NULL;
190     ENGINE *e = NULL, *gen_eng = NULL;
191     EVP_PKEY *pkey = NULL;
192     EVP_PKEY_CTX *genctx = NULL;
193     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
194     X509 *x509ss = NULL;
195     X509_REQ *req = NULL;
196     const EVP_CIPHER *cipher = NULL;
197     const EVP_MD *md_alg = NULL, *digest = NULL;
198     char *extensions = NULL, *infile = NULL;
199     char *outfile = NULL, *keyfile = NULL, *inrand = NULL;
200     char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
201     char *passin = NULL, *passout = NULL, *req_exts = NULL, *subj = NULL;
202     char *template = default_config_file, *keyout = NULL;
203     const char *keyalg = NULL;
204     OPTION_CHOICE o;
205     int ret = 1, x509 = 0, days = 30, i = 0, newreq = 0, verbose = 0;
206     int pkey_type = -1, private = 0;
207     int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
208     int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
209     int nodes = 0, newhdr = 0, subject = 0, pubkey = 0;
210     long newkey = -1;
211     unsigned long chtype = MBSTRING_ASC, nmflag = 0, reqflag = 0;
212     char nmflag_set = 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             e = 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_ANY, &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             nmflag_set = 1;
326             if (!set_name_ex(&nmflag, opt_arg()))
327                 goto opthelp;
328             break;
329         case OPT_REQOPT:
330             if (!set_cert_ex(&reqflag, opt_arg()))
331                 goto opthelp;
332             break;
333         case OPT_TEXT:
334             text = 1;
335             break;
336         case OPT_X509:
337             x509 = 1;
338             break;
339         case OPT_DAYS:
340             days = atoi(opt_arg());
341             break;
342         case OPT_SET_SERIAL:
343             serial = s2i_ASN1_INTEGER(NULL, opt_arg());
344             if (serial == NULL)
345                 goto opthelp;
346             break;
347         case OPT_SUBJECT:
348             subject = 1;
349             break;
350         case OPT_SUBJ:
351             subj = opt_arg();
352             break;
353         case OPT_MULTIVALUE_RDN:
354             multirdn = 1;
355             break;
356         case OPT_EXTENSIONS:
357             extensions = opt_arg();
358             break;
359         case OPT_REQEXTS:
360             req_exts = opt_arg();
361             break;
362         case OPT_MD:
363             if (!opt_md(opt_unknown(), &md_alg))
364                 goto opthelp;
365             digest = md_alg;
366             break;
367         }
368     }
369     argc = opt_num_rest();
370     argv = opt_rest();
371
372     if (!nmflag_set)
373         nmflag = XN_FLAG_ONELINE;
374
375     private = newreq && (pkey == NULL) ? 1 : 0;
376
377     if (!app_passwd(passargin, passargout, &passin, &passout)) {
378         BIO_printf(bio_err, "Error getting passwords\n");
379         goto end;
380     }
381
382     if (verbose)
383         BIO_printf(bio_err, "Using configuration from %s\n", template);
384     req_conf = app_load_config(template);
385     if (!app_load_modules(req_conf))
386         goto end;
387
388     if (req_conf != NULL) {
389         p = NCONF_get_string(req_conf, NULL, "oid_file");
390         if (p == NULL)
391             ERR_clear_error();
392         if (p != NULL) {
393             BIO *oid_bio;
394
395             oid_bio = BIO_new_file(p, "r");
396             if (oid_bio == NULL) {
397                 /*-
398                 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
399                 ERR_print_errors(bio_err);
400                 */
401             } else {
402                 OBJ_create_objects(oid_bio);
403                 BIO_free(oid_bio);
404             }
405         }
406     }
407     if (!add_oid_section(req_conf))
408         goto end;
409
410     if (md_alg == NULL) {
411         p = NCONF_get_string(req_conf, SECTION, "default_md");
412         if (p == NULL)
413             ERR_clear_error();
414         else {
415             if (!opt_md(p, &md_alg))
416                 goto opthelp;
417             digest = md_alg;
418         }
419     }
420
421     if (!extensions) {
422         extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
423         if (!extensions)
424             ERR_clear_error();
425     }
426     if (extensions) {
427         /* Check syntax of file */
428         X509V3_CTX ctx;
429         X509V3_set_ctx_test(&ctx);
430         X509V3_set_nconf(&ctx, req_conf);
431         if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
432             BIO_printf(bio_err,
433                        "Error Loading extension section %s\n", extensions);
434             goto end;
435         }
436     }
437
438     if (!passin) {
439         passin = NCONF_get_string(req_conf, SECTION, "input_password");
440         if (!passin)
441             ERR_clear_error();
442     }
443
444     if (!passout) {
445         passout = NCONF_get_string(req_conf, SECTION, "output_password");
446         if (!passout)
447             ERR_clear_error();
448     }
449
450     p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
451     if (!p)
452         ERR_clear_error();
453
454     if (p && !ASN1_STRING_set_default_mask_asc(p)) {
455         BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
456         goto end;
457     }
458
459     if (chtype != MBSTRING_UTF8) {
460         p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
461         if (!p)
462             ERR_clear_error();
463         else if (strcmp(p, "yes") == 0)
464             chtype = MBSTRING_UTF8;
465     }
466
467     if (!req_exts) {
468         req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
469         if (!req_exts)
470             ERR_clear_error();
471     }
472     if (req_exts) {
473         /* Check syntax of file */
474         X509V3_CTX ctx;
475         X509V3_set_ctx_test(&ctx);
476         X509V3_set_nconf(&ctx, req_conf);
477         if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
478             BIO_printf(bio_err,
479                        "Error Loading request extension section %s\n",
480                        req_exts);
481             goto end;
482         }
483     }
484
485     if (keyfile != NULL) {
486         pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
487         if (!pkey) {
488             /* load_key() has already printed an appropriate message */
489             goto end;
490         } else {
491             char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
492             if (randfile == NULL)
493                 ERR_clear_error();
494             app_RAND_load_file(randfile, 0);
495         }
496     }
497
498     if (newreq && (pkey == NULL)) {
499         char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
500         if (randfile == NULL)
501             ERR_clear_error();
502         app_RAND_load_file(randfile, 0);
503         if (inrand)
504             app_RAND_load_files(inrand);
505
506         if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
507             newkey = DEFAULT_KEY_LENGTH;
508         }
509
510         if (keyalg) {
511             genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
512                                     &keyalgstr, gen_eng);
513             if (!genctx)
514                 goto end;
515         }
516
517         if (newkey < MIN_KEY_LENGTH
518             && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
519             BIO_printf(bio_err, "private key length is too short,\n");
520             BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
521                        MIN_KEY_LENGTH, newkey);
522             goto end;
523         }
524
525         if (!genctx) {
526             genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
527                                     &keyalgstr, gen_eng);
528             if (!genctx)
529                 goto end;
530         }
531
532         if (pkeyopts) {
533             char *genopt;
534             for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
535                 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
536                 if (pkey_ctrl_string(genctx, genopt) <= 0) {
537                     BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
538                     ERR_print_errors(bio_err);
539                     goto end;
540                 }
541             }
542         }
543
544         BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
545                    newkey, keyalgstr);
546
547         EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
548         EVP_PKEY_CTX_set_app_data(genctx, bio_err);
549
550         if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
551             BIO_puts(bio_err, "Error Generating Key\n");
552             goto end;
553         }
554
555         EVP_PKEY_CTX_free(genctx);
556         genctx = NULL;
557
558         app_RAND_write_file(randfile);
559
560         if (keyout == NULL) {
561             keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
562             if (keyout == NULL)
563                 ERR_clear_error();
564         }
565
566         if (keyout == NULL)
567             BIO_printf(bio_err, "writing new private key to stdout\n");
568         else
569             BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
570         out = bio_open_owner(keyout, outformat, private);
571         if (out == NULL)
572             goto end;
573
574         p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
575         if (p == NULL) {
576             ERR_clear_error();
577             p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
578             if (p == NULL)
579                 ERR_clear_error();
580         }
581         if ((p != NULL) && (strcmp(p, "no") == 0))
582             cipher = NULL;
583         if (nodes)
584             cipher = NULL;
585
586         i = 0;
587  loop:
588         assert(private);
589         if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
590                                       NULL, 0, NULL, passout)) {
591             if ((ERR_GET_REASON(ERR_peek_error()) ==
592                  PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
593                 ERR_clear_error();
594                 i++;
595                 goto loop;
596             }
597             goto end;
598         }
599         BIO_free(out);
600         out = NULL;
601         BIO_printf(bio_err, "-----\n");
602     }
603
604     if (!newreq) {
605         in = bio_open_default(infile, 'r', informat);
606         if (in == NULL)
607             goto end;
608
609         if (informat == FORMAT_ASN1)
610             req = d2i_X509_REQ_bio(in, NULL);
611         else
612             req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
613         if (req == NULL) {
614             BIO_printf(bio_err, "unable to load X509 request\n");
615             goto end;
616         }
617     }
618
619     if (newreq || x509) {
620         if (pkey == NULL) {
621             BIO_printf(bio_err, "you need to specify a private key\n");
622             goto end;
623         }
624
625         if (req == NULL) {
626             req = X509_REQ_new();
627             if (req == NULL) {
628                 goto end;
629             }
630
631             i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
632             subj = NULL;        /* done processing '-subj' option */
633             if (!i) {
634                 BIO_printf(bio_err, "problems making Certificate Request\n");
635                 goto end;
636             }
637         }
638         if (x509) {
639             EVP_PKEY *tmppkey;
640             X509V3_CTX ext_ctx;
641             if ((x509ss = X509_new()) == NULL)
642                 goto end;
643
644             /* Set version to V3 */
645             if (extensions && !X509_set_version(x509ss, 2))
646                 goto end;
647             if (serial) {
648                 if (!X509_set_serialNumber(x509ss, serial))
649                     goto end;
650             } else {
651                 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
652                     goto end;
653             }
654
655             if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
656                 goto end;
657             if (!X509_gmtime_adj(X509_get_notBefore(x509ss), 0))
658                 goto end;
659             if (!X509_time_adj_ex(X509_get_notAfter(x509ss), days, 0, NULL))
660                 goto end;
661             if (!X509_set_subject_name
662                 (x509ss, X509_REQ_get_subject_name(req)))
663                 goto end;
664             tmppkey = X509_REQ_get_pubkey(req);
665             if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
666                 goto end;
667             EVP_PKEY_free(tmppkey);
668
669             /* Set up V3 context struct */
670
671             X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
672             X509V3_set_nconf(&ext_ctx, req_conf);
673
674             /* Add extensions */
675             if (extensions && !X509V3_EXT_add_nconf(req_conf,
676                                                     &ext_ctx, extensions,
677                                                     x509ss)) {
678                 BIO_printf(bio_err, "Error Loading extension section %s\n",
679                            extensions);
680                 goto end;
681             }
682
683             i = do_X509_sign(x509ss, pkey, digest, sigopts);
684             if (!i) {
685                 ERR_print_errors(bio_err);
686                 goto end;
687             }
688         } else {
689             X509V3_CTX ext_ctx;
690
691             /* Set up V3 context struct */
692
693             X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
694             X509V3_set_nconf(&ext_ctx, req_conf);
695
696             /* Add extensions */
697             if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf,
698                                                       &ext_ctx, req_exts,
699                                                       req)) {
700                 BIO_printf(bio_err, "Error Loading extension section %s\n",
701                            req_exts);
702                 goto end;
703             }
704             i = do_X509_REQ_sign(req, pkey, digest, sigopts);
705             if (!i) {
706                 ERR_print_errors(bio_err);
707                 goto end;
708             }
709         }
710     }
711
712     if (subj && x509) {
713         BIO_printf(bio_err, "Cannot modify certificate subject\n");
714         goto end;
715     }
716
717     if (subj && !x509) {
718         if (verbose) {
719             BIO_printf(bio_err, "Modifying Request's Subject\n");
720             print_name(bio_err, "old subject=",
721                        X509_REQ_get_subject_name(req), nmflag);
722         }
723
724         if (build_subject(req, subj, chtype, multirdn) == 0) {
725             BIO_printf(bio_err, "ERROR: cannot modify subject\n");
726             ret = 1;
727             goto end;
728         }
729
730         if (verbose) {
731             print_name(bio_err, "new subject=",
732                        X509_REQ_get_subject_name(req), nmflag);
733         }
734     }
735
736     if (verify && !x509) {
737         int tmp = 0;
738
739         if (pkey == NULL) {
740             pkey = X509_REQ_get_pubkey(req);
741             tmp = 1;
742             if (pkey == NULL)
743                 goto end;
744         }
745
746         i = X509_REQ_verify(req, pkey);
747         if (tmp) {
748             EVP_PKEY_free(pkey);
749             pkey = NULL;
750         }
751
752         if (i < 0) {
753             goto end;
754         } else if (i == 0) {
755             BIO_printf(bio_err, "verify failure\n");
756             ERR_print_errors(bio_err);
757         } else                  /* if (i > 0) */
758             BIO_printf(bio_err, "verify OK\n");
759     }
760
761     if (noout && !text && !modulus && !subject && !pubkey) {
762         ret = 0;
763         goto end;
764     }
765
766     out = bio_open_default(outfile,
767                            keyout != NULL && outfile != NULL &&
768                            strcmp(keyout, outfile) == 0 ? 'a' : 'w',
769                            outformat);
770     if (out == NULL)
771         goto end;
772
773     if (pubkey) {
774         EVP_PKEY *tpubkey;
775         tpubkey = X509_REQ_get_pubkey(req);
776         if (tpubkey == NULL) {
777             BIO_printf(bio_err, "Error getting public key\n");
778             ERR_print_errors(bio_err);
779             goto end;
780         }
781         PEM_write_bio_PUBKEY(out, tpubkey);
782         EVP_PKEY_free(tpubkey);
783     }
784
785     if (text) {
786         if (x509)
787             X509_print_ex(out, x509ss, nmflag, reqflag);
788         else
789             X509_REQ_print_ex(out, req, nmflag, reqflag);
790     }
791
792     if (subject) {
793         if (x509)
794             print_name(out, "subject=", X509_get_subject_name(x509ss),
795                        nmflag);
796         else
797             print_name(out, "subject=", X509_REQ_get_subject_name(req),
798                        nmflag);
799     }
800
801     if (modulus) {
802         EVP_PKEY *tpubkey;
803
804         if (x509)
805             tpubkey = X509_get_pubkey(x509ss);
806         else
807             tpubkey = X509_REQ_get_pubkey(req);
808         if (tpubkey == NULL) {
809             fprintf(stdout, "Modulus=unavailable\n");
810             goto end;
811         }
812         fprintf(stdout, "Modulus=");
813 #ifndef OPENSSL_NO_RSA
814         if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA)
815             BN_print(out, EVP_PKEY_get0_RSA(tpubkey)->n);
816         else
817 #endif
818             fprintf(stdout, "Wrong Algorithm type");
819         EVP_PKEY_free(tpubkey);
820         fprintf(stdout, "\n");
821     }
822
823     if (!noout && !x509) {
824         if (outformat == FORMAT_ASN1)
825             i = i2d_X509_REQ_bio(out, req);
826         else if (newhdr)
827             i = PEM_write_bio_X509_REQ_NEW(out, req);
828         else
829             i = PEM_write_bio_X509_REQ(out, req);
830         if (!i) {
831             BIO_printf(bio_err, "unable to write X509 request\n");
832             goto end;
833         }
834     }
835     if (!noout && x509 && (x509ss != NULL)) {
836         if (outformat == FORMAT_ASN1)
837             i = i2d_X509_bio(out, x509ss);
838         else
839             i = PEM_write_bio_X509(out, x509ss);
840         if (!i) {
841             BIO_printf(bio_err, "unable to write X509 certificate\n");
842             goto end;
843         }
844     }
845     ret = 0;
846  end:
847     if (ret) {
848         ERR_print_errors(bio_err);
849     }
850     NCONF_free(req_conf);
851     BIO_free(in);
852     BIO_free_all(out);
853     EVP_PKEY_free(pkey);
854     EVP_PKEY_CTX_free(genctx);
855     sk_OPENSSL_STRING_free(pkeyopts);
856     sk_OPENSSL_STRING_free(sigopts);
857 #ifndef OPENSSL_NO_ENGINE
858     ENGINE_free(gen_eng);
859 #endif
860     OPENSSL_free(keyalgstr);
861     X509_REQ_free(req);
862     X509_free(x509ss);
863     ASN1_INTEGER_free(serial);
864     OPENSSL_free(passin);
865     OPENSSL_free(passout);
866     OBJ_cleanup();
867     return (ret);
868 }
869
870 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
871                     int attribs, unsigned long chtype)
872 {
873     int ret = 0, i;
874     char no_prompt = 0;
875     STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
876     char *tmp, *dn_sect, *attr_sect;
877
878     tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
879     if (tmp == NULL)
880         ERR_clear_error();
881     if ((tmp != NULL) && strcmp(tmp, "no") == 0)
882         no_prompt = 1;
883
884     dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
885     if (dn_sect == NULL) {
886         BIO_printf(bio_err, "unable to find '%s' in config\n",
887                    DISTINGUISHED_NAME);
888         goto err;
889     }
890     dn_sk = NCONF_get_section(req_conf, dn_sect);
891     if (dn_sk == NULL) {
892         BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
893         goto err;
894     }
895
896     attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
897     if (attr_sect == NULL) {
898         ERR_clear_error();
899         attr_sk = NULL;
900     } else {
901         attr_sk = NCONF_get_section(req_conf, attr_sect);
902         if (attr_sk == NULL) {
903             BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
904             goto err;
905         }
906     }
907
908     /* setup version number */
909     if (!X509_REQ_set_version(req, 0L))
910         goto err;               /* version 1 */
911
912     if (subj)
913         i = build_subject(req, subj, chtype, multirdn);
914     else if (no_prompt)
915         i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
916     else
917         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
918                         chtype);
919     if (!i)
920         goto err;
921
922     if (!X509_REQ_set_pubkey(req, pkey))
923         goto err;
924
925     ret = 1;
926  err:
927     return (ret);
928 }
929
930 /*
931  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
932  * where characters may be escaped by \
933  */
934 static int build_subject(X509_REQ *req, char *subject, unsigned long chtype,
935                          int multirdn)
936 {
937     X509_NAME *n;
938
939     if ((n = parse_name(subject, chtype, multirdn)) == NULL)
940         return 0;
941
942     if (!X509_REQ_set_subject_name(req, n)) {
943         X509_NAME_free(n);
944         return 0;
945     }
946     X509_NAME_free(n);
947     return 1;
948 }
949
950 static int prompt_info(X509_REQ *req,
951                        STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
952                        STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
953                        int attribs, unsigned long chtype)
954 {
955     int i;
956     char *p, *q;
957     char buf[100];
958     int nid, mval;
959     long n_min, n_max;
960     char *type, *value;
961     const char *def;
962     CONF_VALUE *v;
963     X509_NAME *subj;
964     subj = X509_REQ_get_subject_name(req);
965
966     if (!batch) {
967         BIO_printf(bio_err,
968                    "You are about to be asked to enter information that will be incorporated\n");
969         BIO_printf(bio_err, "into your certificate request.\n");
970         BIO_printf(bio_err,
971                    "What you are about to enter is what is called a Distinguished Name or a DN.\n");
972         BIO_printf(bio_err,
973                    "There are quite a few fields but you can leave some blank\n");
974         BIO_printf(bio_err,
975                    "For some fields there will be a default value,\n");
976         BIO_printf(bio_err,
977                    "If you enter '.', the field will be left blank.\n");
978         BIO_printf(bio_err, "-----\n");
979     }
980
981     if (sk_CONF_VALUE_num(dn_sk)) {
982         i = -1;
983  start:for (;;) {
984             i++;
985             if (sk_CONF_VALUE_num(dn_sk) <= i)
986                 break;
987
988             v = sk_CONF_VALUE_value(dn_sk, i);
989             p = q = NULL;
990             type = v->name;
991             if (!check_end(type, "_min") || !check_end(type, "_max") ||
992                 !check_end(type, "_default") || !check_end(type, "_value"))
993                 continue;
994             /*
995              * Skip past any leading X. X: X, etc to allow for multiple
996              * instances
997              */
998             for (p = v->name; *p; p++)
999                 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1000                     p++;
1001                     if (*p)
1002                         type = p;
1003                     break;
1004                 }
1005             if (*type == '+') {
1006                 mval = -1;
1007                 type++;
1008             } else
1009                 mval = 0;
1010             /* If OBJ not recognised ignore it */
1011             if ((nid = OBJ_txt2nid(type)) == NID_undef)
1012                 goto start;
1013             if (BIO_snprintf(buf, sizeof buf, "%s_default", v->name)
1014                 >= (int)sizeof(buf)) {
1015                 BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1016                 return 0;
1017             }
1018
1019             if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1020                 ERR_clear_error();
1021                 def = "";
1022             }
1023
1024             BIO_snprintf(buf, sizeof buf, "%s_value", v->name);
1025             if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1026                 ERR_clear_error();
1027                 value = NULL;
1028             }
1029
1030             BIO_snprintf(buf, sizeof buf, "%s_min", v->name);
1031             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1032                 ERR_clear_error();
1033                 n_min = -1;
1034             }
1035
1036             BIO_snprintf(buf, sizeof buf, "%s_max", v->name);
1037             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1038                 ERR_clear_error();
1039                 n_max = -1;
1040             }
1041
1042             if (!add_DN_object(subj, v->value, def, value, nid,
1043                                n_min, n_max, chtype, mval))
1044                 return 0;
1045         }
1046         if (X509_NAME_entry_count(subj) == 0) {
1047             BIO_printf(bio_err,
1048                        "error, no objects specified in config file\n");
1049             return 0;
1050         }
1051
1052         if (attribs) {
1053             if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1054                 && (!batch)) {
1055                 BIO_printf(bio_err,
1056                            "\nPlease enter the following 'extra' attributes\n");
1057                 BIO_printf(bio_err,
1058                            "to be sent with your certificate request\n");
1059             }
1060
1061             i = -1;
1062  start2:   for (;;) {
1063                 i++;
1064                 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1065                     break;
1066
1067                 v = sk_CONF_VALUE_value(attr_sk, i);
1068                 type = v->name;
1069                 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1070                     goto start2;
1071
1072                 if (BIO_snprintf(buf, sizeof buf, "%s_default", type)
1073                     >= (int)sizeof(buf)) {
1074                     BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1075                     return 0;
1076                 }
1077
1078                 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1079                     == NULL) {
1080                     ERR_clear_error();
1081                     def = "";
1082                 }
1083
1084                 BIO_snprintf(buf, sizeof buf, "%s_value", type);
1085                 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1086                     == NULL) {
1087                     ERR_clear_error();
1088                     value = NULL;
1089                 }
1090
1091                 BIO_snprintf(buf, sizeof buf, "%s_min", type);
1092                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1093                     ERR_clear_error();
1094                     n_min = -1;
1095                 }
1096
1097                 BIO_snprintf(buf, sizeof buf, "%s_max", type);
1098                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1099                     ERR_clear_error();
1100                     n_max = -1;
1101                 }
1102
1103                 if (!add_attribute_object(req,
1104                                           v->value, def, value, nid, n_min,
1105                                           n_max, chtype))
1106                     return 0;
1107             }
1108         }
1109     } else {
1110         BIO_printf(bio_err, "No template, please set one up.\n");
1111         return 0;
1112     }
1113
1114     return 1;
1115
1116 }
1117
1118 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1119                      STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1120                      unsigned long chtype)
1121 {
1122     int i;
1123     char *p, *q;
1124     char *type;
1125     CONF_VALUE *v;
1126     X509_NAME *subj;
1127
1128     subj = X509_REQ_get_subject_name(req);
1129
1130     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1131         int mval;
1132         v = sk_CONF_VALUE_value(dn_sk, i);
1133         p = q = NULL;
1134         type = v->name;
1135         /*
1136          * Skip past any leading X. X: X, etc to allow for multiple instances
1137          */
1138         for (p = v->name; *p; p++)
1139 #ifndef CHARSET_EBCDIC
1140             if ((*p == ':') || (*p == ',') || (*p == '.')) {
1141 #else
1142             if ((*p == os_toascii[':']) || (*p == os_toascii[','])
1143                 || (*p == os_toascii['.'])) {
1144 #endif
1145                 p++;
1146                 if (*p)
1147                     type = p;
1148                 break;
1149             }
1150 #ifndef CHARSET_EBCDIC
1151         if (*p == '+')
1152 #else
1153         if (*p == os_toascii['+'])
1154 #endif
1155         {
1156             p++;
1157             mval = -1;
1158         } else
1159             mval = 0;
1160         if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1161                                         (unsigned char *)v->value, -1, -1,
1162                                         mval))
1163             return 0;
1164
1165     }
1166
1167     if (!X509_NAME_entry_count(subj)) {
1168         BIO_printf(bio_err, "error, no objects specified in config file\n");
1169         return 0;
1170     }
1171     if (attribs) {
1172         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1173             v = sk_CONF_VALUE_value(attr_sk, i);
1174             if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1175                                            (unsigned char *)v->value, -1))
1176                 return 0;
1177         }
1178     }
1179     return 1;
1180 }
1181
1182 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1183                          char *value, int nid, int n_min, int n_max,
1184                          unsigned long chtype, int mval)
1185 {
1186     int i, ret = 0;
1187     char buf[1024];
1188  start:
1189     if (!batch)
1190         BIO_printf(bio_err, "%s [%s]:", text, def);
1191     (void)BIO_flush(bio_err);
1192     if (value != NULL) {
1193         OPENSSL_strlcpy(buf, value, sizeof buf);
1194         OPENSSL_strlcat(buf, "\n", sizeof buf);
1195         BIO_printf(bio_err, "%s\n", value);
1196     } else {
1197         buf[0] = '\0';
1198         if (!batch) {
1199             if (!fgets(buf, sizeof buf, stdin))
1200                 return 0;
1201         } else {
1202             buf[0] = '\n';
1203             buf[1] = '\0';
1204         }
1205     }
1206
1207     if (buf[0] == '\0')
1208         return (0);
1209     else if (buf[0] == '\n') {
1210         if ((def == NULL) || (def[0] == '\0'))
1211             return (1);
1212         OPENSSL_strlcpy(buf, def, sizeof buf);
1213         OPENSSL_strlcat(buf, "\n", sizeof buf);
1214     } else if ((buf[0] == '.') && (buf[1] == '\n'))
1215         return (1);
1216
1217     i = strlen(buf);
1218     if (buf[i - 1] != '\n') {
1219         BIO_printf(bio_err, "weird input :-(\n");
1220         return (0);
1221     }
1222     buf[--i] = '\0';
1223 #ifdef CHARSET_EBCDIC
1224     ebcdic2ascii(buf, buf, i);
1225 #endif
1226     if (!req_check_len(i, n_min, n_max)) {
1227         if (batch || value)
1228             return 0;
1229         goto start;
1230     }
1231
1232     if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1233                                     (unsigned char *)buf, -1, -1, mval))
1234         goto err;
1235     ret = 1;
1236  err:
1237     return (ret);
1238 }
1239
1240 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1241                                 char *value, int nid, int n_min,
1242                                 int n_max, unsigned long chtype)
1243 {
1244     int i;
1245     static char buf[1024];
1246
1247  start:
1248     if (!batch)
1249         BIO_printf(bio_err, "%s [%s]:", text, def);
1250     (void)BIO_flush(bio_err);
1251     if (value != NULL) {
1252         OPENSSL_strlcpy(buf, value, sizeof buf);
1253         OPENSSL_strlcat(buf, "\n", sizeof buf);
1254         BIO_printf(bio_err, "%s\n", value);
1255     } else {
1256         buf[0] = '\0';
1257         if (!batch) {
1258             if (!fgets(buf, sizeof buf, stdin))
1259                 return 0;
1260         } else {
1261             buf[0] = '\n';
1262             buf[1] = '\0';
1263         }
1264     }
1265
1266     if (buf[0] == '\0')
1267         return (0);
1268     else if (buf[0] == '\n') {
1269         if ((def == NULL) || (def[0] == '\0'))
1270             return (1);
1271         OPENSSL_strlcpy(buf, def, sizeof buf);
1272         OPENSSL_strlcat(buf, "\n", sizeof buf);
1273     } else if ((buf[0] == '.') && (buf[1] == '\n'))
1274         return (1);
1275
1276     i = strlen(buf);
1277     if (buf[i - 1] != '\n') {
1278         BIO_printf(bio_err, "weird input :-(\n");
1279         return (0);
1280     }
1281     buf[--i] = '\0';
1282 #ifdef CHARSET_EBCDIC
1283     ebcdic2ascii(buf, buf, i);
1284 #endif
1285     if (!req_check_len(i, n_min, n_max)) {
1286         if (batch || value)
1287             return 0;
1288         goto start;
1289     }
1290
1291     if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1292                                    (unsigned char *)buf, -1)) {
1293         BIO_printf(bio_err, "Error adding attribute\n");
1294         ERR_print_errors(bio_err);
1295         goto err;
1296     }
1297
1298     return (1);
1299  err:
1300     return (0);
1301 }
1302
1303 static int req_check_len(int len, int n_min, int n_max)
1304 {
1305     if ((n_min > 0) && (len < n_min)) {
1306         BIO_printf(bio_err,
1307                    "string is too short, it needs to be at least %d bytes long\n",
1308                    n_min);
1309         return (0);
1310     }
1311     if ((n_max >= 0) && (len > n_max)) {
1312         BIO_printf(bio_err,
1313                    "string is too long, it needs to be less than  %d bytes long\n",
1314                    n_max);
1315         return (0);
1316     }
1317     return (1);
1318 }
1319
1320 /* Check if the end of a string matches 'end' */
1321 static int check_end(const char *str, const char *end)
1322 {
1323     int elen, slen;
1324     const char *tmp;
1325     elen = strlen(end);
1326     slen = strlen(str);
1327     if (elen > slen)
1328         return 1;
1329     tmp = str + slen - elen;
1330     return strcmp(tmp, end);
1331 }
1332
1333 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1334                                     int *pkey_type, long *pkeylen,
1335                                     char **palgnam, ENGINE *keygen_engine)
1336 {
1337     EVP_PKEY_CTX *gctx = NULL;
1338     EVP_PKEY *param = NULL;
1339     long keylen = -1;
1340     BIO *pbio = NULL;
1341     const char *paramfile = NULL;
1342
1343     if (gstr == NULL) {
1344         *pkey_type = EVP_PKEY_RSA;
1345         keylen = *pkeylen;
1346     } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1347         *pkey_type = EVP_PKEY_RSA;
1348         keylen = atol(gstr);
1349         *pkeylen = keylen;
1350     } else if (strncmp(gstr, "param:", 6) == 0)
1351         paramfile = gstr + 6;
1352     else {
1353         const char *p = strchr(gstr, ':');
1354         int len;
1355         ENGINE *tmpeng;
1356         const EVP_PKEY_ASN1_METHOD *ameth;
1357
1358         if (p)
1359             len = p - gstr;
1360         else
1361             len = strlen(gstr);
1362         /*
1363          * The lookup of a the string will cover all engines so keep a note
1364          * of the implementation.
1365          */
1366
1367         ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1368
1369         if (!ameth) {
1370             BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1371             return NULL;
1372         }
1373
1374         EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1375 #ifndef OPENSSL_NO_ENGINE
1376         if (tmpeng)
1377             ENGINE_finish(tmpeng);
1378 #endif
1379         if (*pkey_type == EVP_PKEY_RSA) {
1380             if (p) {
1381                 keylen = atol(p + 1);
1382                 *pkeylen = keylen;
1383             } else
1384                 keylen = *pkeylen;
1385         } else if (p)
1386             paramfile = p + 1;
1387     }
1388
1389     if (paramfile) {
1390         pbio = BIO_new_file(paramfile, "r");
1391         if (!pbio) {
1392             BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1393             return NULL;
1394         }
1395         param = PEM_read_bio_Parameters(pbio, NULL);
1396
1397         if (!param) {
1398             X509 *x;
1399             (void)BIO_reset(pbio);
1400             x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1401             if (x) {
1402                 param = X509_get_pubkey(x);
1403                 X509_free(x);
1404             }
1405         }
1406
1407         BIO_free(pbio);
1408
1409         if (!param) {
1410             BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1411             return NULL;
1412         }
1413         if (*pkey_type == -1)
1414             *pkey_type = EVP_PKEY_id(param);
1415         else if (*pkey_type != EVP_PKEY_base_id(param)) {
1416             BIO_printf(bio_err, "Key Type does not match parameters\n");
1417             EVP_PKEY_free(param);
1418             return NULL;
1419         }
1420     }
1421
1422     if (palgnam) {
1423         const EVP_PKEY_ASN1_METHOD *ameth;
1424         ENGINE *tmpeng;
1425         const char *anam;
1426         ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1427         if (!ameth) {
1428             BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1429             return NULL;
1430         }
1431         EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1432         *palgnam = OPENSSL_strdup(anam);
1433 #ifndef OPENSSL_NO_ENGINE
1434         if (tmpeng)
1435             ENGINE_finish(tmpeng);
1436 #endif
1437     }
1438
1439     if (param) {
1440         gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1441         *pkeylen = EVP_PKEY_bits(param);
1442         EVP_PKEY_free(param);
1443     } else
1444         gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1445
1446     if (gctx == NULL) {
1447         BIO_puts(bio_err, "Error allocating keygen context\n");
1448         ERR_print_errors(bio_err);
1449         return NULL;
1450     }
1451
1452     if (EVP_PKEY_keygen_init(gctx) <= 0) {
1453         BIO_puts(bio_err, "Error initializing keygen context\n");
1454         ERR_print_errors(bio_err);
1455         EVP_PKEY_CTX_free(gctx);
1456         return NULL;
1457     }
1458 #ifndef OPENSSL_NO_RSA
1459     if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1460         if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1461             BIO_puts(bio_err, "Error setting RSA keysize\n");
1462             ERR_print_errors(bio_err);
1463             EVP_PKEY_CTX_free(gctx);
1464             return NULL;
1465         }
1466     }
1467 #endif
1468
1469     return gctx;
1470 }
1471
1472 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1473 {
1474     char c = '*';
1475     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1476     int p;
1477     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1478     if (p == 0)
1479         c = '.';
1480     if (p == 1)
1481         c = '+';
1482     if (p == 2)
1483         c = '*';
1484     if (p == 3)
1485         c = '\n';
1486     BIO_write(b, &c, 1);
1487     (void)BIO_flush(b);
1488     return 1;
1489 }
1490
1491 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1492                         const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1493 {
1494     EVP_PKEY_CTX *pkctx = NULL;
1495     int i;
1496
1497     if (ctx == NULL)
1498         return 0;
1499     if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1500         return 0;
1501     for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1502         char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1503         if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1504             BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1505             ERR_print_errors(bio_err);
1506             return 0;
1507         }
1508     }
1509     return 1;
1510 }
1511
1512 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1513                  STACK_OF(OPENSSL_STRING) *sigopts)
1514 {
1515     int rv;
1516     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1517
1518     rv = do_sign_init(mctx, pkey, md, sigopts);
1519     /* Note: X509_sign_ctx() calls ASN1_item_sign_ctx(), which destroys
1520      * the EVP_MD_CTX we send it, so only destroy it here if the former
1521      * isn't called */
1522     if (rv > 0)
1523         rv = X509_sign_ctx(x, mctx);
1524     else
1525         EVP_MD_CTX_free(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 = EVP_MD_CTX_new();
1534     rv = do_sign_init(mctx, pkey, md, sigopts);
1535     /* Note: X509_REQ_sign_ctx() calls ASN1_item_sign_ctx(), which destroys
1536      * the EVP_MD_CTX we send it, so only destroy it here if the former
1537      * isn't called */
1538     if (rv > 0)
1539         rv = X509_REQ_sign_ctx(x, mctx);
1540     else
1541         EVP_MD_CTX_free(mctx);
1542     return rv > 0 ? 1 : 0;
1543 }
1544
1545 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1546                      STACK_OF(OPENSSL_STRING) *sigopts)
1547 {
1548     int rv;
1549     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1550     rv = do_sign_init(mctx, pkey, md, sigopts);
1551     /* Note: X509_CRL_sign_ctx() calls ASN1_item_sign_ctx(), which destroys
1552      * the EVP_MD_CTX we send it, so only destroy it here if the former
1553      * isn't called */
1554     if (rv > 0)
1555         rv = X509_CRL_sign_ctx(x, mctx);
1556     else
1557         EVP_MD_CTX_free(mctx);
1558     return rv > 0 ? 1 : 0;
1559 }