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