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