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