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