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