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