Fix a shadow symbol warning
[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 (!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             BN_print(out, EVP_PKEY_get0_RSA(tpubkey)->n);
816         else
817 #endif
818             fprintf(stdout, "Wrong Algorithm type");
819         EVP_PKEY_free(tpubkey);
820         fprintf(stdout, "\n");
821     }
822
823     if (!noout && !x509) {
824         if (outformat == FORMAT_ASN1)
825             i = i2d_X509_REQ_bio(out, req);
826         else if (newhdr)
827             i = PEM_write_bio_X509_REQ_NEW(out, req);
828         else
829             i = PEM_write_bio_X509_REQ(out, req);
830         if (!i) {
831             BIO_printf(bio_err, "unable to write X509 request\n");
832             goto end;
833         }
834     }
835     if (!noout && x509 && (x509ss != NULL)) {
836         if (outformat == FORMAT_ASN1)
837             i = i2d_X509_bio(out, x509ss);
838         else
839             i = PEM_write_bio_X509(out, x509ss);
840         if (!i) {
841             BIO_printf(bio_err, "unable to write X509 certificate\n");
842             goto end;
843         }
844     }
845     ret = 0;
846  end:
847     if (ret) {
848         ERR_print_errors(bio_err);
849     }
850     NCONF_free(req_conf);
851     BIO_free(in);
852     BIO_free_all(out);
853     EVP_PKEY_free(pkey);
854     EVP_PKEY_CTX_free(genctx);
855     sk_OPENSSL_STRING_free(pkeyopts);
856     sk_OPENSSL_STRING_free(sigopts);
857 #ifndef OPENSSL_NO_ENGINE
858     ENGINE_free(gen_eng);
859 #endif
860     OPENSSL_free(keyalgstr);
861     X509_REQ_free(req);
862     X509_free(x509ss);
863     ASN1_INTEGER_free(serial);
864     if (passin != nofree_passin)
865         OPENSSL_free(passin);
866     if (passout != nofree_passout)
867         OPENSSL_free(passout);
868     OBJ_cleanup();
869     return (ret);
870 }
871
872 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
873                     int attribs, unsigned long chtype)
874 {
875     int ret = 0, i;
876     char no_prompt = 0;
877     STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
878     char *tmp, *dn_sect, *attr_sect;
879
880     tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
881     if (tmp == NULL)
882         ERR_clear_error();
883     if ((tmp != NULL) && strcmp(tmp, "no") == 0)
884         no_prompt = 1;
885
886     dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
887     if (dn_sect == NULL) {
888         BIO_printf(bio_err, "unable to find '%s' in config\n",
889                    DISTINGUISHED_NAME);
890         goto err;
891     }
892     dn_sk = NCONF_get_section(req_conf, dn_sect);
893     if (dn_sk == NULL) {
894         BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
895         goto err;
896     }
897
898     attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
899     if (attr_sect == NULL) {
900         ERR_clear_error();
901         attr_sk = NULL;
902     } else {
903         attr_sk = NCONF_get_section(req_conf, attr_sect);
904         if (attr_sk == NULL) {
905             BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
906             goto err;
907         }
908     }
909
910     /* setup version number */
911     if (!X509_REQ_set_version(req, 0L))
912         goto err;               /* version 1 */
913
914     if (subj)
915         i = build_subject(req, subj, chtype, multirdn);
916     else if (no_prompt)
917         i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
918     else
919         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
920                         chtype);
921     if (!i)
922         goto err;
923
924     if (!X509_REQ_set_pubkey(req, pkey))
925         goto err;
926
927     ret = 1;
928  err:
929     return (ret);
930 }
931
932 /*
933  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
934  * where characters may be escaped by \
935  */
936 static int build_subject(X509_REQ *req, char *subject, unsigned long chtype,
937                          int multirdn)
938 {
939     X509_NAME *n;
940
941     if ((n = parse_name(subject, chtype, multirdn)) == NULL)
942         return 0;
943
944     if (!X509_REQ_set_subject_name(req, n)) {
945         X509_NAME_free(n);
946         return 0;
947     }
948     X509_NAME_free(n);
949     return 1;
950 }
951
952 static int prompt_info(X509_REQ *req,
953                        STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
954                        STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
955                        int attribs, unsigned long chtype)
956 {
957     int i;
958     char *p, *q;
959     char buf[100];
960     int nid, mval;
961     long n_min, n_max;
962     char *type, *value;
963     const char *def;
964     CONF_VALUE *v;
965     X509_NAME *subj;
966     subj = X509_REQ_get_subject_name(req);
967
968     if (!batch) {
969         BIO_printf(bio_err,
970                    "You are about to be asked to enter information that will be incorporated\n");
971         BIO_printf(bio_err, "into your certificate request.\n");
972         BIO_printf(bio_err,
973                    "What you are about to enter is what is called a Distinguished Name or a DN.\n");
974         BIO_printf(bio_err,
975                    "There are quite a few fields but you can leave some blank\n");
976         BIO_printf(bio_err,
977                    "For some fields there will be a default value,\n");
978         BIO_printf(bio_err,
979                    "If you enter '.', the field will be left blank.\n");
980         BIO_printf(bio_err, "-----\n");
981     }
982
983     if (sk_CONF_VALUE_num(dn_sk)) {
984         i = -1;
985  start:for (;;) {
986             i++;
987             if (sk_CONF_VALUE_num(dn_sk) <= i)
988                 break;
989
990             v = sk_CONF_VALUE_value(dn_sk, i);
991             p = q = NULL;
992             type = v->name;
993             if (!check_end(type, "_min") || !check_end(type, "_max") ||
994                 !check_end(type, "_default") || !check_end(type, "_value"))
995                 continue;
996             /*
997              * Skip past any leading X. X: X, etc to allow for multiple
998              * instances
999              */
1000             for (p = v->name; *p; p++)
1001                 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1002                     p++;
1003                     if (*p)
1004                         type = p;
1005                     break;
1006                 }
1007             if (*type == '+') {
1008                 mval = -1;
1009                 type++;
1010             } else
1011                 mval = 0;
1012             /* If OBJ not recognised ignore it */
1013             if ((nid = OBJ_txt2nid(type)) == NID_undef)
1014                 goto start;
1015             if (BIO_snprintf(buf, sizeof buf, "%s_default", v->name)
1016                 >= (int)sizeof(buf)) {
1017                 BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1018                 return 0;
1019             }
1020
1021             if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1022                 ERR_clear_error();
1023                 def = "";
1024             }
1025
1026             BIO_snprintf(buf, sizeof buf, "%s_value", v->name);
1027             if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1028                 ERR_clear_error();
1029                 value = NULL;
1030             }
1031
1032             BIO_snprintf(buf, sizeof buf, "%s_min", v->name);
1033             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1034                 ERR_clear_error();
1035                 n_min = -1;
1036             }
1037
1038             BIO_snprintf(buf, sizeof buf, "%s_max", v->name);
1039             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1040                 ERR_clear_error();
1041                 n_max = -1;
1042             }
1043
1044             if (!add_DN_object(subj, v->value, def, value, nid,
1045                                n_min, n_max, chtype, mval))
1046                 return 0;
1047         }
1048         if (X509_NAME_entry_count(subj) == 0) {
1049             BIO_printf(bio_err,
1050                        "error, no objects specified in config file\n");
1051             return 0;
1052         }
1053
1054         if (attribs) {
1055             if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1056                 && (!batch)) {
1057                 BIO_printf(bio_err,
1058                            "\nPlease enter the following 'extra' attributes\n");
1059                 BIO_printf(bio_err,
1060                            "to be sent with your certificate request\n");
1061             }
1062
1063             i = -1;
1064  start2:   for (;;) {
1065                 i++;
1066                 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1067                     break;
1068
1069                 v = sk_CONF_VALUE_value(attr_sk, i);
1070                 type = v->name;
1071                 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1072                     goto start2;
1073
1074                 if (BIO_snprintf(buf, sizeof buf, "%s_default", type)
1075                     >= (int)sizeof(buf)) {
1076                     BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1077                     return 0;
1078                 }
1079
1080                 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1081                     == NULL) {
1082                     ERR_clear_error();
1083                     def = "";
1084                 }
1085
1086                 BIO_snprintf(buf, sizeof buf, "%s_value", type);
1087                 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1088                     == NULL) {
1089                     ERR_clear_error();
1090                     value = NULL;
1091                 }
1092
1093                 BIO_snprintf(buf, sizeof buf, "%s_min", type);
1094                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1095                     ERR_clear_error();
1096                     n_min = -1;
1097                 }
1098
1099                 BIO_snprintf(buf, sizeof buf, "%s_max", type);
1100                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1101                     ERR_clear_error();
1102                     n_max = -1;
1103                 }
1104
1105                 if (!add_attribute_object(req,
1106                                           v->value, def, value, nid, n_min,
1107                                           n_max, chtype))
1108                     return 0;
1109             }
1110         }
1111     } else {
1112         BIO_printf(bio_err, "No template, please set one up.\n");
1113         return 0;
1114     }
1115
1116     return 1;
1117
1118 }
1119
1120 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1121                      STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1122                      unsigned long chtype)
1123 {
1124     int i, spec_char, plus_char;
1125     char *p, *q;
1126     char *type;
1127     CONF_VALUE *v;
1128     X509_NAME *subj;
1129
1130     subj = X509_REQ_get_subject_name(req);
1131
1132     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1133         int mval;
1134         v = sk_CONF_VALUE_value(dn_sk, i);
1135         p = q = NULL;
1136         type = v->name;
1137         /*
1138          * Skip past any leading X. X: X, etc to allow for multiple instances
1139          */
1140         for (p = v->name; *p; p++) {
1141 #ifndef CHARSET_EBCDIC
1142             spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1143 #else
1144             spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1145                     || (*p == os_toascii['.']));
1146 #endif
1147             if (spec_char) {
1148                 p++;
1149                 if (*p)
1150                     type = p;
1151                 break;
1152             }
1153         }
1154 #ifndef CHARSET_EBCDIC
1155         plus_char = (*p == '+');
1156 #else
1157         plus_char = (*p == os_toascii['+']);
1158 #endif
1159         if (plus_char) {
1160             p++;
1161             mval = -1;
1162         } else
1163             mval = 0;
1164         if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1165                                         (unsigned char *)v->value, -1, -1,
1166                                         mval))
1167             return 0;
1168
1169     }
1170
1171     if (!X509_NAME_entry_count(subj)) {
1172         BIO_printf(bio_err, "error, no objects specified in config file\n");
1173         return 0;
1174     }
1175     if (attribs) {
1176         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1177             v = sk_CONF_VALUE_value(attr_sk, i);
1178             if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1179                                            (unsigned char *)v->value, -1))
1180                 return 0;
1181         }
1182     }
1183     return 1;
1184 }
1185
1186 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1187                          char *value, int nid, int n_min, int n_max,
1188                          unsigned long chtype, int mval)
1189 {
1190     int i, ret = 0;
1191     char buf[1024];
1192  start:
1193     if (!batch)
1194         BIO_printf(bio_err, "%s [%s]:", text, def);
1195     (void)BIO_flush(bio_err);
1196     if (value != NULL) {
1197         OPENSSL_strlcpy(buf, value, sizeof buf);
1198         OPENSSL_strlcat(buf, "\n", sizeof buf);
1199         BIO_printf(bio_err, "%s\n", value);
1200     } else {
1201         buf[0] = '\0';
1202         if (!batch) {
1203             if (!fgets(buf, sizeof buf, stdin))
1204                 return 0;
1205         } else {
1206             buf[0] = '\n';
1207             buf[1] = '\0';
1208         }
1209     }
1210
1211     if (buf[0] == '\0')
1212         return (0);
1213     else if (buf[0] == '\n') {
1214         if ((def == NULL) || (def[0] == '\0'))
1215             return (1);
1216         OPENSSL_strlcpy(buf, def, sizeof buf);
1217         OPENSSL_strlcat(buf, "\n", sizeof buf);
1218     } else if ((buf[0] == '.') && (buf[1] == '\n'))
1219         return (1);
1220
1221     i = strlen(buf);
1222     if (buf[i - 1] != '\n') {
1223         BIO_printf(bio_err, "weird input :-(\n");
1224         return (0);
1225     }
1226     buf[--i] = '\0';
1227 #ifdef CHARSET_EBCDIC
1228     ebcdic2ascii(buf, buf, i);
1229 #endif
1230     if (!req_check_len(i, n_min, n_max)) {
1231         if (batch || value)
1232             return 0;
1233         goto start;
1234     }
1235
1236     if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1237                                     (unsigned char *)buf, -1, -1, mval))
1238         goto err;
1239     ret = 1;
1240  err:
1241     return (ret);
1242 }
1243
1244 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1245                                 char *value, int nid, int n_min,
1246                                 int n_max, unsigned long chtype)
1247 {
1248     int i;
1249     static char buf[1024];
1250
1251  start:
1252     if (!batch)
1253         BIO_printf(bio_err, "%s [%s]:", text, def);
1254     (void)BIO_flush(bio_err);
1255     if (value != NULL) {
1256         OPENSSL_strlcpy(buf, value, sizeof buf);
1257         OPENSSL_strlcat(buf, "\n", sizeof buf);
1258         BIO_printf(bio_err, "%s\n", value);
1259     } else {
1260         buf[0] = '\0';
1261         if (!batch) {
1262             if (!fgets(buf, sizeof buf, stdin))
1263                 return 0;
1264         } else {
1265             buf[0] = '\n';
1266             buf[1] = '\0';
1267         }
1268     }
1269
1270     if (buf[0] == '\0')
1271         return (0);
1272     else if (buf[0] == '\n') {
1273         if ((def == NULL) || (def[0] == '\0'))
1274             return (1);
1275         OPENSSL_strlcpy(buf, def, sizeof buf);
1276         OPENSSL_strlcat(buf, "\n", sizeof buf);
1277     } else if ((buf[0] == '.') && (buf[1] == '\n'))
1278         return (1);
1279
1280     i = strlen(buf);
1281     if (buf[i - 1] != '\n') {
1282         BIO_printf(bio_err, "weird input :-(\n");
1283         return (0);
1284     }
1285     buf[--i] = '\0';
1286 #ifdef CHARSET_EBCDIC
1287     ebcdic2ascii(buf, buf, i);
1288 #endif
1289     if (!req_check_len(i, n_min, n_max)) {
1290         if (batch || value)
1291             return 0;
1292         goto start;
1293     }
1294
1295     if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1296                                    (unsigned char *)buf, -1)) {
1297         BIO_printf(bio_err, "Error adding attribute\n");
1298         ERR_print_errors(bio_err);
1299         goto err;
1300     }
1301
1302     return (1);
1303  err:
1304     return (0);
1305 }
1306
1307 static int req_check_len(int len, int n_min, int n_max)
1308 {
1309     if ((n_min > 0) && (len < n_min)) {
1310         BIO_printf(bio_err,
1311                    "string is too short, it needs to be at least %d bytes long\n",
1312                    n_min);
1313         return (0);
1314     }
1315     if ((n_max >= 0) && (len > n_max)) {
1316         BIO_printf(bio_err,
1317                    "string is too long, it needs to be less than  %d bytes long\n",
1318                    n_max);
1319         return (0);
1320     }
1321     return (1);
1322 }
1323
1324 /* Check if the end of a string matches 'end' */
1325 static int check_end(const char *str, const char *end)
1326 {
1327     int elen, slen;
1328     const char *tmp;
1329     elen = strlen(end);
1330     slen = strlen(str);
1331     if (elen > slen)
1332         return 1;
1333     tmp = str + slen - elen;
1334     return strcmp(tmp, end);
1335 }
1336
1337 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1338                                     int *pkey_type, long *pkeylen,
1339                                     char **palgnam, ENGINE *keygen_engine)
1340 {
1341     EVP_PKEY_CTX *gctx = NULL;
1342     EVP_PKEY *param = NULL;
1343     long keylen = -1;
1344     BIO *pbio = NULL;
1345     const char *paramfile = NULL;
1346
1347     if (gstr == NULL) {
1348         *pkey_type = EVP_PKEY_RSA;
1349         keylen = *pkeylen;
1350     } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1351         *pkey_type = EVP_PKEY_RSA;
1352         keylen = atol(gstr);
1353         *pkeylen = keylen;
1354     } else if (strncmp(gstr, "param:", 6) == 0)
1355         paramfile = gstr + 6;
1356     else {
1357         const char *p = strchr(gstr, ':');
1358         int len;
1359         ENGINE *tmpeng;
1360         const EVP_PKEY_ASN1_METHOD *ameth;
1361
1362         if (p)
1363             len = p - gstr;
1364         else
1365             len = strlen(gstr);
1366         /*
1367          * The lookup of a the string will cover all engines so keep a note
1368          * of the implementation.
1369          */
1370
1371         ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1372
1373         if (!ameth) {
1374             BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1375             return NULL;
1376         }
1377
1378         EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1379 #ifndef OPENSSL_NO_ENGINE
1380         ENGINE_finish(tmpeng);
1381 #endif
1382         if (*pkey_type == EVP_PKEY_RSA) {
1383             if (p) {
1384                 keylen = atol(p + 1);
1385                 *pkeylen = keylen;
1386             } else
1387                 keylen = *pkeylen;
1388         } else if (p)
1389             paramfile = p + 1;
1390     }
1391
1392     if (paramfile) {
1393         pbio = BIO_new_file(paramfile, "r");
1394         if (!pbio) {
1395             BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1396             return NULL;
1397         }
1398         param = PEM_read_bio_Parameters(pbio, NULL);
1399
1400         if (!param) {
1401             X509 *x;
1402             (void)BIO_reset(pbio);
1403             x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1404             if (x) {
1405                 param = X509_get_pubkey(x);
1406                 X509_free(x);
1407             }
1408         }
1409
1410         BIO_free(pbio);
1411
1412         if (!param) {
1413             BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1414             return NULL;
1415         }
1416         if (*pkey_type == -1)
1417             *pkey_type = EVP_PKEY_id(param);
1418         else if (*pkey_type != EVP_PKEY_base_id(param)) {
1419             BIO_printf(bio_err, "Key Type does not match parameters\n");
1420             EVP_PKEY_free(param);
1421             return NULL;
1422         }
1423     }
1424
1425     if (palgnam) {
1426         const EVP_PKEY_ASN1_METHOD *ameth;
1427         ENGINE *tmpeng;
1428         const char *anam;
1429         ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1430         if (!ameth) {
1431             BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1432             return NULL;
1433         }
1434         EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1435         *palgnam = OPENSSL_strdup(anam);
1436 #ifndef OPENSSL_NO_ENGINE
1437         ENGINE_finish(tmpeng);
1438 #endif
1439     }
1440
1441     if (param) {
1442         gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1443         *pkeylen = EVP_PKEY_bits(param);
1444         EVP_PKEY_free(param);
1445     } else
1446         gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1447
1448     if (gctx == NULL) {
1449         BIO_puts(bio_err, "Error allocating keygen context\n");
1450         ERR_print_errors(bio_err);
1451         return NULL;
1452     }
1453
1454     if (EVP_PKEY_keygen_init(gctx) <= 0) {
1455         BIO_puts(bio_err, "Error initializing keygen context\n");
1456         ERR_print_errors(bio_err);
1457         EVP_PKEY_CTX_free(gctx);
1458         return NULL;
1459     }
1460 #ifndef OPENSSL_NO_RSA
1461     if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1462         if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1463             BIO_puts(bio_err, "Error setting RSA keysize\n");
1464             ERR_print_errors(bio_err);
1465             EVP_PKEY_CTX_free(gctx);
1466             return NULL;
1467         }
1468     }
1469 #endif
1470
1471     return gctx;
1472 }
1473
1474 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1475 {
1476     char c = '*';
1477     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1478     int p;
1479     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1480     if (p == 0)
1481         c = '.';
1482     if (p == 1)
1483         c = '+';
1484     if (p == 2)
1485         c = '*';
1486     if (p == 3)
1487         c = '\n';
1488     BIO_write(b, &c, 1);
1489     (void)BIO_flush(b);
1490     return 1;
1491 }
1492
1493 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1494                         const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1495 {
1496     EVP_PKEY_CTX *pkctx = NULL;
1497     int i;
1498
1499     if (ctx == NULL)
1500         return 0;
1501     if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1502         return 0;
1503     for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1504         char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1505         if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1506             BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1507             ERR_print_errors(bio_err);
1508             return 0;
1509         }
1510     }
1511     return 1;
1512 }
1513
1514 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1515                  STACK_OF(OPENSSL_STRING) *sigopts)
1516 {
1517     int rv;
1518     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1519
1520     rv = do_sign_init(mctx, pkey, md, sigopts);
1521     if (rv > 0)
1522         rv = X509_sign_ctx(x, mctx);
1523     EVP_MD_CTX_free(mctx);
1524     return rv > 0 ? 1 : 0;
1525 }
1526
1527 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1528                      STACK_OF(OPENSSL_STRING) *sigopts)
1529 {
1530     int rv;
1531     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1532     rv = do_sign_init(mctx, pkey, md, sigopts);
1533     if (rv > 0)
1534         rv = X509_REQ_sign_ctx(x, mctx);
1535     EVP_MD_CTX_free(mctx);
1536     return rv > 0 ? 1 : 0;
1537 }
1538
1539 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1540                      STACK_OF(OPENSSL_STRING) *sigopts)
1541 {
1542     int rv;
1543     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1544     rv = do_sign_init(mctx, pkey, md, sigopts);
1545     if (rv > 0)
1546         rv = X509_CRL_sign_ctx(x, mctx);
1547     EVP_MD_CTX_free(mctx);
1548     return rv > 0 ? 1 : 0;
1549 }