Big apps cleanup (option-parsing, etc)
[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     {"keygen_engine", OPT_KEYGEN_ENGINE, 's'},
140     {"key", OPT_KEY, '<', "Use the private key contained in file"},
141     {"keyform", OPT_KEYFORM, 'F', "Key file format"},
142     {"pubkey", OPT_PUBKEY, '-', "Output public key"},
143     {"new", OPT_NEW, '-', "New request"},
144     {"config", OPT_CONFIG, '<', "Request template file"},
145     {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
146     {"passin", OPT_PASSIN, 's', "Private key password source"},
147     {"passout", OPT_PASSOUT, 's'},
148     {"rand", OPT_RAND, 's',
149      "Load the file(s) into the random number generator"},
150     {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
151     {"pkeyopt", OPT_PKEYOPT, 's'},
152     {"sigopt", OPT_SIGOPT, 's'},
153     {"batch", OPT_BATCH, '-',
154      "Do not ask anything during request generation"},
155     {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
156     {"modulus", OPT_MODULUS, '-', "RSA modulus"},
157     {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
158     {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
159     {"noout", OPT_NOOUT, '-', "Do not output REQ"},
160     {"verbose", OPT_VERBOSE, '-'},
161     {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
162     {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
163     {"reqopt", OPT_REQOPT, 's', "Various request text options"},
164     {"text", OPT_TEXT, '-', "Text form of request"},
165     {"x509", OPT_X509, '-',
166      "Output a x509 structure instead of a cert request"},
167     {"asn1-kludge", OPT_ASN1_KLUDGE, '-',
168      "Output the request in a format that is wrong"},
169     {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
170     {"no-asn1-kludge", OPT_NO_ASN1_KLUDGE, '-'},
171     {"subject", OPT_SUBJECT, 's', "Output the request's subject"},
172     {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
173      "Enable support for multivalued RDNs"},
174     {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
175     {"set-serial", OPT_SET_SERIAL, 'p', "Serial number to use"},
176     {"extensions", OPT_EXTENSIONS, 's',
177      "Cert extension section (override value in config file)"},
178     {"reqexts", OPT_REQEXTS, 's',
179      "Request extension section (override value in config file)"},
180 #ifndef OPENSSL_NO_ENGINE
181     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
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 *engine = NULL, *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 #ifndef OPENSSL_NO_ENGINE
239         case OPT_ENGINE:
240             engine = optarg;
241             break;
242         case OPT_KEYGEN_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 end;
247             }
248             break;
249 #endif
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 #ifndef OPENSSL_NO_ENGINE
502     e = setup_engine(engine, 0);
503 #endif
504
505     if (keyfile != NULL) {
506         pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
507         if (!pkey) {
508             /* load_key() has already printed an appropriate message */
509             goto end;
510         } else {
511             char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
512             if (randfile == NULL)
513                 ERR_clear_error();
514             app_RAND_load_file(randfile, 0);
515         }
516     }
517
518     if (newreq && (pkey == NULL)) {
519         char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
520         if (randfile == NULL)
521             ERR_clear_error();
522         app_RAND_load_file(randfile, 0);
523         if (inrand)
524             app_RAND_load_files(inrand);
525
526         if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
527             newkey = DEFAULT_KEY_LENGTH;
528         }
529
530         if (keyalg) {
531             genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
532                                     &keyalgstr, gen_eng);
533             if (!genctx)
534                 goto end;
535         }
536
537         if (newkey < MIN_KEY_LENGTH
538             && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
539             BIO_printf(bio_err, "private key length is too short,\n");
540             BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
541                        MIN_KEY_LENGTH, newkey);
542             goto end;
543         }
544
545         if (!genctx) {
546             genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
547                                     &keyalgstr, gen_eng);
548             if (!genctx)
549                 goto end;
550         }
551
552         if (pkeyopts) {
553             char *genopt;
554             for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
555                 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
556                 if (pkey_ctrl_string(genctx, genopt) <= 0) {
557                     BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
558                     ERR_print_errors(bio_err);
559                     goto end;
560                 }
561             }
562         }
563
564         BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
565                    newkey, keyalgstr);
566
567         EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
568         EVP_PKEY_CTX_set_app_data(genctx, bio_err);
569
570         if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
571             BIO_puts(bio_err, "Error Generating Key\n");
572             goto end;
573         }
574
575         EVP_PKEY_CTX_free(genctx);
576         genctx = NULL;
577
578         app_RAND_write_file(randfile);
579
580         if (keyout == NULL) {
581             keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
582             if (keyout == NULL)
583                 ERR_clear_error();
584         }
585
586         if (keyout == NULL)
587             BIO_printf(bio_err, "writing new private key to stdout\n");
588         else
589             BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
590         out = bio_open_default(keyout, "w");
591         if (out == NULL)
592             goto end;
593
594         p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
595         if (p == NULL) {
596             ERR_clear_error();
597             p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
598             if (p == NULL)
599                 ERR_clear_error();
600         }
601         if ((p != NULL) && (strcmp(p, "no") == 0))
602             cipher = NULL;
603         if (nodes)
604             cipher = NULL;
605
606         i = 0;
607  loop:
608         if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
609                                       NULL, 0, NULL, passout)) {
610             if ((ERR_GET_REASON(ERR_peek_error()) ==
611                  PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
612                 ERR_clear_error();
613                 i++;
614                 goto loop;
615             }
616             goto end;
617         }
618         BIO_printf(bio_err, "-----\n");
619     }
620
621     if (!newreq) {
622         /*
623          * Since we are using a pre-existing certificate request, the kludge
624          * 'format' info should not be changed.
625          */
626         kludge = -1;
627         in = bio_open_default(infile, RB(informat));
628         if (in == NULL)
629             goto end;
630
631         if (informat == FORMAT_ASN1)
632             req = d2i_X509_REQ_bio(in, NULL);
633         else
634             req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
635         if (req == NULL) {
636             BIO_printf(bio_err, "unable to load X509 request\n");
637             goto end;
638         }
639     }
640
641     if (newreq || x509) {
642         if (pkey == NULL) {
643             BIO_printf(bio_err, "you need to specify a private key\n");
644             goto end;
645         }
646
647         if (req == NULL) {
648             req = X509_REQ_new();
649             if (req == NULL) {
650                 goto end;
651             }
652
653             i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
654             subj = NULL;        /* done processing '-subj' option */
655             if ((kludge > 0)
656                 && !sk_X509_ATTRIBUTE_num(req->req_info->attributes)) {
657                 sk_X509_ATTRIBUTE_free(req->req_info->attributes);
658                 req->req_info->attributes = NULL;
659             }
660             if (!i) {
661                 BIO_printf(bio_err, "problems making Certificate Request\n");
662                 goto end;
663             }
664         }
665         if (x509) {
666             EVP_PKEY *tmppkey;
667             X509V3_CTX ext_ctx;
668             if ((x509ss = X509_new()) == NULL)
669                 goto end;
670
671             /* Set version to V3 */
672             if (extensions && !X509_set_version(x509ss, 2))
673                 goto end;
674             if (serial) {
675                 if (!X509_set_serialNumber(x509ss, serial))
676                     goto end;
677             } else {
678                 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
679                     goto end;
680             }
681
682             if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
683                 goto end;
684             if (!X509_gmtime_adj(X509_get_notBefore(x509ss), 0))
685                 goto end;
686             if (!X509_time_adj_ex(X509_get_notAfter(x509ss), days, 0, NULL))
687                 goto end;
688             if (!X509_set_subject_name
689                 (x509ss, X509_REQ_get_subject_name(req)))
690                 goto end;
691             tmppkey = X509_REQ_get_pubkey(req);
692             if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
693                 goto end;
694             EVP_PKEY_free(tmppkey);
695
696             /* Set up V3 context struct */
697
698             X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
699             X509V3_set_nconf(&ext_ctx, req_conf);
700
701             /* Add extensions */
702             if (extensions && !X509V3_EXT_add_nconf(req_conf,
703                                                     &ext_ctx, extensions,
704                                                     x509ss)) {
705                 BIO_printf(bio_err, "Error Loading extension section %s\n",
706                            extensions);
707                 goto end;
708             }
709
710             i = do_X509_sign(x509ss, pkey, digest, sigopts);
711             if (!i) {
712                 ERR_print_errors(bio_err);
713                 goto end;
714             }
715         } else {
716             X509V3_CTX ext_ctx;
717
718             /* Set up V3 context struct */
719
720             X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
721             X509V3_set_nconf(&ext_ctx, req_conf);
722
723             /* Add extensions */
724             if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf,
725                                                       &ext_ctx, req_exts,
726                                                       req)) {
727                 BIO_printf(bio_err, "Error Loading extension section %s\n",
728                            req_exts);
729                 goto end;
730             }
731             i = do_X509_REQ_sign(req, pkey, digest, sigopts);
732             if (!i) {
733                 ERR_print_errors(bio_err);
734                 goto end;
735             }
736         }
737     }
738
739     if (subj && x509) {
740         BIO_printf(bio_err, "Cannot modify certificate subject\n");
741         goto end;
742     }
743
744     if (subj && !x509) {
745         if (verbose) {
746             BIO_printf(bio_err, "Modifying Request's Subject\n");
747             print_name(bio_err, "old subject=",
748                        X509_REQ_get_subject_name(req), nmflag);
749         }
750
751         if (build_subject(req, subj, chtype, multirdn) == 0) {
752             BIO_printf(bio_err, "ERROR: cannot modify subject\n");
753             ret = 1;
754             goto end;
755         }
756
757         req->req_info->enc.modified = 1;
758
759         if (verbose) {
760             print_name(bio_err, "new subject=",
761                        X509_REQ_get_subject_name(req), nmflag);
762         }
763     }
764
765     if (verify && !x509) {
766         int tmp = 0;
767
768         if (pkey == NULL) {
769             pkey = X509_REQ_get_pubkey(req);
770             tmp = 1;
771             if (pkey == NULL)
772                 goto end;
773         }
774
775         i = X509_REQ_verify(req, pkey);
776         if (tmp) {
777             EVP_PKEY_free(pkey);
778             pkey = NULL;
779         }
780
781         if (i < 0) {
782             goto end;
783         } else if (i == 0) {
784             BIO_printf(bio_err, "verify failure\n");
785             ERR_print_errors(bio_err);
786         } else                  /* if (i > 0) */
787             BIO_printf(bio_err, "verify OK\n");
788     }
789
790     if (noout && !text && !modulus && !subject && !pubkey) {
791         ret = 0;
792         goto end;
793     }
794
795     out = bio_open_default(outfile,
796                            keyout != NULL && outfile != NULL &&
797                            strcmp(keyout, outfile) == 0 ? "a" : "w");
798     if (out == NULL)
799         goto end;
800
801     if (pubkey) {
802         EVP_PKEY *tpubkey;
803         tpubkey = X509_REQ_get_pubkey(req);
804         if (tpubkey == NULL) {
805             BIO_printf(bio_err, "Error getting public key\n");
806             ERR_print_errors(bio_err);
807             goto end;
808         }
809         PEM_write_bio_PUBKEY(out, tpubkey);
810         EVP_PKEY_free(tpubkey);
811     }
812
813     if (text) {
814         if (x509)
815             X509_print_ex(out, x509ss, nmflag, reqflag);
816         else
817             X509_REQ_print_ex(out, req, nmflag, reqflag);
818     }
819
820     if (subject) {
821         if (x509)
822             print_name(out, "subject=", X509_get_subject_name(x509ss),
823                        nmflag);
824         else
825             print_name(out, "subject=", X509_REQ_get_subject_name(req),
826                        nmflag);
827     }
828
829     if (modulus) {
830         EVP_PKEY *tpubkey;
831
832         if (x509)
833             tpubkey = X509_get_pubkey(x509ss);
834         else
835             tpubkey = X509_REQ_get_pubkey(req);
836         if (tpubkey == NULL) {
837             fprintf(stdout, "Modulus=unavailable\n");
838             goto end;
839         }
840         fprintf(stdout, "Modulus=");
841 #ifndef OPENSSL_NO_RSA
842         if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA)
843             BN_print(out, tpubkey->pkey.rsa->n);
844         else
845 #endif
846             fprintf(stdout, "Wrong Algorithm type");
847         EVP_PKEY_free(tpubkey);
848         fprintf(stdout, "\n");
849     }
850
851     if (!noout && !x509) {
852         if (outformat == FORMAT_ASN1)
853             i = i2d_X509_REQ_bio(out, req);
854         else if (newhdr)
855             i = PEM_write_bio_X509_REQ_NEW(out, req);
856         else
857             i = PEM_write_bio_X509_REQ(out, req);
858         if (!i) {
859             BIO_printf(bio_err, "unable to write X509 request\n");
860             goto end;
861         }
862     }
863     if (!noout && x509 && (x509ss != NULL)) {
864         if (outformat == FORMAT_ASN1)
865             i = i2d_X509_bio(out, x509ss);
866         else
867             i = PEM_write_bio_X509(out, x509ss);
868         if (!i) {
869             BIO_printf(bio_err, "unable to write X509 certificate\n");
870             goto end;
871         }
872     }
873     ret = 0;
874  end:
875     if (ret) {
876         ERR_print_errors(bio_err);
877     }
878     if ((req_conf != NULL) && (req_conf != config))
879         NCONF_free(req_conf);
880     BIO_free(in);
881     BIO_free_all(out);
882     EVP_PKEY_free(pkey);
883     EVP_PKEY_CTX_free(genctx);
884     if (pkeyopts)
885         sk_OPENSSL_STRING_free(pkeyopts);
886     if (sigopts)
887         sk_OPENSSL_STRING_free(sigopts);
888 #ifndef OPENSSL_NO_ENGINE
889     if (gen_eng)
890         ENGINE_free(gen_eng);
891 #endif
892     if (keyalgstr)
893         OPENSSL_free(keyalgstr);
894     X509_REQ_free(req);
895     X509_free(x509ss);
896     ASN1_INTEGER_free(serial);
897     if (passargin && passin)
898         OPENSSL_free(passin);
899     if (passargout && passout)
900         OPENSSL_free(passout);
901     OBJ_cleanup();
902     return (ret);
903 }
904
905 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
906                     int attribs, unsigned long chtype)
907 {
908     int ret = 0, i;
909     char no_prompt = 0;
910     STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
911     char *tmp, *dn_sect, *attr_sect;
912
913     tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
914     if (tmp == NULL)
915         ERR_clear_error();
916     if ((tmp != NULL) && !strcmp(tmp, "no"))
917         no_prompt = 1;
918
919     dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
920     if (dn_sect == NULL) {
921         BIO_printf(bio_err, "unable to find '%s' in config\n",
922                    DISTINGUISHED_NAME);
923         goto err;
924     }
925     dn_sk = NCONF_get_section(req_conf, dn_sect);
926     if (dn_sk == NULL) {
927         BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
928         goto err;
929     }
930
931     attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
932     if (attr_sect == NULL) {
933         ERR_clear_error();
934         attr_sk = NULL;
935     } else {
936         attr_sk = NCONF_get_section(req_conf, attr_sect);
937         if (attr_sk == NULL) {
938             BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
939             goto err;
940         }
941     }
942
943     /* setup version number */
944     if (!X509_REQ_set_version(req, 0L))
945         goto err;               /* version 1 */
946
947     if (subj)
948         i = build_subject(req, subj, chtype, multirdn);
949     else if (no_prompt)
950         i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
951     else
952         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
953                         chtype);
954     if (!i)
955         goto err;
956
957     if (!X509_REQ_set_pubkey(req, pkey))
958         goto err;
959
960     ret = 1;
961  err:
962     return (ret);
963 }
964
965 /*
966  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
967  * where characters may be escaped by \
968  */
969 static int build_subject(X509_REQ *req, char *subject, unsigned long chtype,
970                          int multirdn)
971 {
972     X509_NAME *n;
973
974     if (!(n = parse_name(subject, chtype, multirdn)))
975         return 0;
976
977     if (!X509_REQ_set_subject_name(req, n)) {
978         X509_NAME_free(n);
979         return 0;
980     }
981     X509_NAME_free(n);
982     return 1;
983 }
984
985 static int prompt_info(X509_REQ *req,
986                        STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
987                        STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
988                        int attribs, unsigned long chtype)
989 {
990     int i;
991     char *p, *q;
992     char buf[100];
993     int nid, mval;
994     long n_min, n_max;
995     char *type, *value;
996     const char *def;
997     CONF_VALUE *v;
998     X509_NAME *subj;
999     subj = X509_REQ_get_subject_name(req);
1000
1001     if (!batch) {
1002         BIO_printf(bio_err,
1003                    "You are about to be asked to enter information that will be incorporated\n");
1004         BIO_printf(bio_err, "into your certificate request.\n");
1005         BIO_printf(bio_err,
1006                    "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1007         BIO_printf(bio_err,
1008                    "There are quite a few fields but you can leave some blank\n");
1009         BIO_printf(bio_err,
1010                    "For some fields there will be a default value,\n");
1011         BIO_printf(bio_err,
1012                    "If you enter '.', the field will be left blank.\n");
1013         BIO_printf(bio_err, "-----\n");
1014     }
1015
1016     if (sk_CONF_VALUE_num(dn_sk)) {
1017         i = -1;
1018  start:for (;;) {
1019             i++;
1020             if (sk_CONF_VALUE_num(dn_sk) <= i)
1021                 break;
1022
1023             v = sk_CONF_VALUE_value(dn_sk, i);
1024             p = q = NULL;
1025             type = v->name;
1026             if (!check_end(type, "_min") || !check_end(type, "_max") ||
1027                 !check_end(type, "_default") || !check_end(type, "_value"))
1028                 continue;
1029             /*
1030              * Skip past any leading X. X: X, etc to allow for multiple
1031              * instances
1032              */
1033             for (p = v->name; *p; p++)
1034                 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1035                     p++;
1036                     if (*p)
1037                         type = p;
1038                     break;
1039                 }
1040             if (*type == '+') {
1041                 mval = -1;
1042                 type++;
1043             } else
1044                 mval = 0;
1045             /* If OBJ not recognised ignore it */
1046             if ((nid = OBJ_txt2nid(type)) == NID_undef)
1047                 goto start;
1048             if (BIO_snprintf(buf, sizeof buf, "%s_default", v->name)
1049                 >= (int)sizeof(buf)) {
1050                 BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1051                 return 0;
1052             }
1053
1054             if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1055                 ERR_clear_error();
1056                 def = "";
1057             }
1058
1059             BIO_snprintf(buf, sizeof buf, "%s_value", v->name);
1060             if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1061                 ERR_clear_error();
1062                 value = NULL;
1063             }
1064
1065             BIO_snprintf(buf, sizeof buf, "%s_min", v->name);
1066             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1067                 ERR_clear_error();
1068                 n_min = -1;
1069             }
1070
1071             BIO_snprintf(buf, sizeof buf, "%s_max", v->name);
1072             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1073                 ERR_clear_error();
1074                 n_max = -1;
1075             }
1076
1077             if (!add_DN_object(subj, v->value, def, value, nid,
1078                                n_min, n_max, chtype, mval))
1079                 return 0;
1080         }
1081         if (X509_NAME_entry_count(subj) == 0) {
1082             BIO_printf(bio_err,
1083                        "error, no objects specified in config file\n");
1084             return 0;
1085         }
1086
1087         if (attribs) {
1088             if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1089                 && (!batch)) {
1090                 BIO_printf(bio_err,
1091                            "\nPlease enter the following 'extra' attributes\n");
1092                 BIO_printf(bio_err,
1093                            "to be sent with your certificate request\n");
1094             }
1095
1096             i = -1;
1097  start2:   for (;;) {
1098                 i++;
1099                 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1100                     break;
1101
1102                 v = sk_CONF_VALUE_value(attr_sk, i);
1103                 type = v->name;
1104                 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1105                     goto start2;
1106
1107                 if (BIO_snprintf(buf, sizeof buf, "%s_default", type)
1108                     >= (int)sizeof(buf)) {
1109                     BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1110                     return 0;
1111                 }
1112
1113                 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1114                     == NULL) {
1115                     ERR_clear_error();
1116                     def = "";
1117                 }
1118
1119                 BIO_snprintf(buf, sizeof buf, "%s_value", type);
1120                 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1121                     == NULL) {
1122                     ERR_clear_error();
1123                     value = NULL;
1124                 }
1125
1126                 BIO_snprintf(buf, sizeof buf, "%s_min", type);
1127                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1128                     ERR_clear_error();
1129                     n_min = -1;
1130                 }
1131
1132                 BIO_snprintf(buf, sizeof buf, "%s_max", type);
1133                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1134                     ERR_clear_error();
1135                     n_max = -1;
1136                 }
1137
1138                 if (!add_attribute_object(req,
1139                                           v->value, def, value, nid, n_min,
1140                                           n_max, chtype))
1141                     return 0;
1142             }
1143         }
1144     } else {
1145         BIO_printf(bio_err, "No template, please set one up.\n");
1146         return 0;
1147     }
1148
1149     return 1;
1150
1151 }
1152
1153 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1154                      STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1155                      unsigned long chtype)
1156 {
1157     int i;
1158     char *p, *q;
1159     char *type;
1160     CONF_VALUE *v;
1161     X509_NAME *subj;
1162
1163     subj = X509_REQ_get_subject_name(req);
1164
1165     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1166         int mval;
1167         v = sk_CONF_VALUE_value(dn_sk, i);
1168         p = q = NULL;
1169         type = v->name;
1170         /*
1171          * Skip past any leading X. X: X, etc to allow for multiple instances
1172          */
1173         for (p = v->name; *p; p++)
1174 #ifndef CHARSET_EBCDIC
1175             if ((*p == ':') || (*p == ',') || (*p == '.')) {
1176 #else
1177             if ((*p == os_toascii[':']) || (*p == os_toascii[','])
1178                 || (*p == os_toascii['.'])) {
1179 #endif
1180                 p++;
1181                 if (*p)
1182                     type = p;
1183                 break;
1184             }
1185 #ifndef CHARSET_EBCDIC
1186         if (*p == '+')
1187 #else
1188         if (*p == os_toascii['+'])
1189 #endif
1190         {
1191             p++;
1192             mval = -1;
1193         } else
1194             mval = 0;
1195         if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1196                                         (unsigned char *)v->value, -1, -1,
1197                                         mval))
1198             return 0;
1199
1200     }
1201
1202     if (!X509_NAME_entry_count(subj)) {
1203         BIO_printf(bio_err, "error, no objects specified in config file\n");
1204         return 0;
1205     }
1206     if (attribs) {
1207         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1208             v = sk_CONF_VALUE_value(attr_sk, i);
1209             if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1210                                            (unsigned char *)v->value, -1))
1211                 return 0;
1212         }
1213     }
1214     return 1;
1215 }
1216
1217 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1218                          char *value, int nid, int n_min, int n_max,
1219                          unsigned long chtype, int mval)
1220 {
1221     int i, ret = 0;
1222     char buf[1024];
1223  start:
1224     if (!batch)
1225         BIO_printf(bio_err, "%s [%s]:", text, def);
1226     (void)BIO_flush(bio_err);
1227     if (value != NULL) {
1228         BUF_strlcpy(buf, value, sizeof buf);
1229         BUF_strlcat(buf, "\n", sizeof buf);
1230         BIO_printf(bio_err, "%s\n", value);
1231     } else {
1232         buf[0] = '\0';
1233         if (!batch) {
1234             if (!fgets(buf, sizeof buf, stdin))
1235                 return 0;
1236         } else {
1237             buf[0] = '\n';
1238             buf[1] = '\0';
1239         }
1240     }
1241
1242     if (buf[0] == '\0')
1243         return (0);
1244     else if (buf[0] == '\n') {
1245         if ((def == NULL) || (def[0] == '\0'))
1246             return (1);
1247         BUF_strlcpy(buf, def, sizeof buf);
1248         BUF_strlcat(buf, "\n", sizeof buf);
1249     } else if ((buf[0] == '.') && (buf[1] == '\n'))
1250         return (1);
1251
1252     i = strlen(buf);
1253     if (buf[i - 1] != '\n') {
1254         BIO_printf(bio_err, "weird input :-(\n");
1255         return (0);
1256     }
1257     buf[--i] = '\0';
1258 #ifdef CHARSET_EBCDIC
1259     ebcdic2ascii(buf, buf, i);
1260 #endif
1261     if (!req_check_len(i, n_min, n_max)) {
1262         if (batch || value)
1263             return 0;
1264         goto start;
1265     }
1266
1267     if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1268                                     (unsigned char *)buf, -1, -1, mval))
1269         goto err;
1270     ret = 1;
1271  err:
1272     return (ret);
1273 }
1274
1275 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1276                                 char *value, int nid, int n_min,
1277                                 int n_max, unsigned long chtype)
1278 {
1279     int i;
1280     static char buf[1024];
1281
1282  start:
1283     if (!batch)
1284         BIO_printf(bio_err, "%s [%s]:", text, def);
1285     (void)BIO_flush(bio_err);
1286     if (value != NULL) {
1287         BUF_strlcpy(buf, value, sizeof buf);
1288         BUF_strlcat(buf, "\n", sizeof buf);
1289         BIO_printf(bio_err, "%s\n", value);
1290     } else {
1291         buf[0] = '\0';
1292         if (!batch) {
1293             if (!fgets(buf, sizeof buf, stdin))
1294                 return 0;
1295         } else {
1296             buf[0] = '\n';
1297             buf[1] = '\0';
1298         }
1299     }
1300
1301     if (buf[0] == '\0')
1302         return (0);
1303     else if (buf[0] == '\n') {
1304         if ((def == NULL) || (def[0] == '\0'))
1305             return (1);
1306         BUF_strlcpy(buf, def, sizeof buf);
1307         BUF_strlcat(buf, "\n", sizeof buf);
1308     } else if ((buf[0] == '.') && (buf[1] == '\n'))
1309         return (1);
1310
1311     i = strlen(buf);
1312     if (buf[i - 1] != '\n') {
1313         BIO_printf(bio_err, "weird input :-(\n");
1314         return (0);
1315     }
1316     buf[--i] = '\0';
1317 #ifdef CHARSET_EBCDIC
1318     ebcdic2ascii(buf, buf, i);
1319 #endif
1320     if (!req_check_len(i, n_min, n_max)) {
1321         if (batch || value)
1322             return 0;
1323         goto start;
1324     }
1325
1326     if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1327                                    (unsigned char *)buf, -1)) {
1328         BIO_printf(bio_err, "Error adding attribute\n");
1329         ERR_print_errors(bio_err);
1330         goto err;
1331     }
1332
1333     return (1);
1334  err:
1335     return (0);
1336 }
1337
1338 static int req_check_len(int len, int n_min, int n_max)
1339 {
1340     if ((n_min > 0) && (len < n_min)) {
1341         BIO_printf(bio_err,
1342                    "string is too short, it needs to be at least %d bytes long\n",
1343                    n_min);
1344         return (0);
1345     }
1346     if ((n_max >= 0) && (len > n_max)) {
1347         BIO_printf(bio_err,
1348                    "string is too long, it needs to be less than  %d bytes long\n",
1349                    n_max);
1350         return (0);
1351     }
1352     return (1);
1353 }
1354
1355 /* Check if the end of a string matches 'end' */
1356 static int check_end(const char *str, const char *end)
1357 {
1358     int elen, slen;
1359     const char *tmp;
1360     elen = strlen(end);
1361     slen = strlen(str);
1362     if (elen > slen)
1363         return 1;
1364     tmp = str + slen - elen;
1365     return strcmp(tmp, end);
1366 }
1367
1368 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1369                                     int *pkey_type, long *pkeylen,
1370                                     char **palgnam, ENGINE *keygen_engine)
1371 {
1372     EVP_PKEY_CTX *gctx = NULL;
1373     EVP_PKEY *param = NULL;
1374     long keylen = -1;
1375     BIO *pbio = NULL;
1376     const char *paramfile = NULL;
1377
1378     if (gstr == NULL) {
1379         *pkey_type = EVP_PKEY_RSA;
1380         keylen = *pkeylen;
1381     } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1382         *pkey_type = EVP_PKEY_RSA;
1383         keylen = atol(gstr);
1384         *pkeylen = keylen;
1385     } else if (!strncmp(gstr, "param:", 6))
1386         paramfile = gstr + 6;
1387     else {
1388         const char *p = strchr(gstr, ':');
1389         int len;
1390         ENGINE *tmpeng;
1391         const EVP_PKEY_ASN1_METHOD *ameth;
1392
1393         if (p)
1394             len = p - gstr;
1395         else
1396             len = strlen(gstr);
1397         /*
1398          * The lookup of a the string will cover all engines so keep a note
1399          * of the implementation.
1400          */
1401
1402         ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1403
1404         if (!ameth) {
1405             BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1406             return NULL;
1407         }
1408
1409         EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1410 #ifndef OPENSSL_NO_ENGINE
1411         if (tmpeng)
1412             ENGINE_finish(tmpeng);
1413 #endif
1414         if (*pkey_type == EVP_PKEY_RSA) {
1415             if (p) {
1416                 keylen = atol(p + 1);
1417                 *pkeylen = keylen;
1418             } else
1419                 keylen = *pkeylen;
1420         } else if (p)
1421             paramfile = p + 1;
1422     }
1423
1424     if (paramfile) {
1425         pbio = BIO_new_file(paramfile, "r");
1426         if (!pbio) {
1427             BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1428             return NULL;
1429         }
1430         param = PEM_read_bio_Parameters(pbio, NULL);
1431
1432         if (!param) {
1433             X509 *x;
1434             (void)BIO_reset(pbio);
1435             x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1436             if (x) {
1437                 param = X509_get_pubkey(x);
1438                 X509_free(x);
1439             }
1440         }
1441
1442         BIO_free(pbio);
1443
1444         if (!param) {
1445             BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1446             return NULL;
1447         }
1448         if (*pkey_type == -1)
1449             *pkey_type = EVP_PKEY_id(param);
1450         else if (*pkey_type != EVP_PKEY_base_id(param)) {
1451             BIO_printf(bio_err, "Key Type does not match parameters\n");
1452             EVP_PKEY_free(param);
1453             return NULL;
1454         }
1455     }
1456
1457     if (palgnam) {
1458         const EVP_PKEY_ASN1_METHOD *ameth;
1459         ENGINE *tmpeng;
1460         const char *anam;
1461         ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1462         if (!ameth) {
1463             BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1464             return NULL;
1465         }
1466         EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1467         *palgnam = BUF_strdup(anam);
1468 #ifndef OPENSSL_NO_ENGINE
1469         if (tmpeng)
1470             ENGINE_finish(tmpeng);
1471 #endif
1472     }
1473
1474     if (param) {
1475         gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1476         *pkeylen = EVP_PKEY_bits(param);
1477         EVP_PKEY_free(param);
1478     } else
1479         gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1480
1481     if (!gctx) {
1482         BIO_puts(bio_err, "Error allocating keygen context\n");
1483         ERR_print_errors(bio_err);
1484         return NULL;
1485     }
1486
1487     if (EVP_PKEY_keygen_init(gctx) <= 0) {
1488         BIO_puts(bio_err, "Error initializing keygen context\n");
1489         ERR_print_errors(bio_err);
1490         return NULL;
1491     }
1492 #ifndef OPENSSL_NO_RSA
1493     if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1494         if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1495             BIO_puts(bio_err, "Error setting RSA keysize\n");
1496             ERR_print_errors(bio_err);
1497             EVP_PKEY_CTX_free(gctx);
1498             return NULL;
1499         }
1500     }
1501 #endif
1502
1503     return gctx;
1504 }
1505
1506 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1507 {
1508     char c = '*';
1509     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1510     int p;
1511     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1512     if (p == 0)
1513         c = '.';
1514     if (p == 1)
1515         c = '+';
1516     if (p == 2)
1517         c = '*';
1518     if (p == 3)
1519         c = '\n';
1520     BIO_write(b, &c, 1);
1521     (void)BIO_flush(b);
1522     return 1;
1523 }
1524
1525 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1526                         const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1527 {
1528     EVP_PKEY_CTX *pkctx = NULL;
1529     int i;
1530
1531     EVP_MD_CTX_init(ctx);
1532     if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1533         return 0;
1534     for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1535         char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1536         if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1537             BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1538             ERR_print_errors(bio_err);
1539             return 0;
1540         }
1541     }
1542     return 1;
1543 }
1544
1545 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1546                  STACK_OF(OPENSSL_STRING) *sigopts)
1547 {
1548     int rv;
1549     EVP_MD_CTX mctx;
1550
1551     EVP_MD_CTX_init(&mctx);
1552     rv = do_sign_init(&mctx, pkey, md, sigopts);
1553     if (rv > 0)
1554         rv = X509_sign_ctx(x, &mctx);
1555     EVP_MD_CTX_cleanup(&mctx);
1556     return rv > 0 ? 1 : 0;
1557 }
1558
1559 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1560                      STACK_OF(OPENSSL_STRING) *sigopts)
1561 {
1562     int rv;
1563     EVP_MD_CTX mctx;
1564
1565     EVP_MD_CTX_init(&mctx);
1566     rv = do_sign_init(&mctx, pkey, md, sigopts);
1567     if (rv > 0)
1568         rv = X509_REQ_sign_ctx(x, &mctx);
1569     EVP_MD_CTX_cleanup(&mctx);
1570     return rv > 0 ? 1 : 0;
1571 }
1572
1573 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1574                      STACK_OF(OPENSSL_STRING) *sigopts)
1575 {
1576     int rv;
1577     EVP_MD_CTX mctx;
1578
1579     EVP_MD_CTX_init(&mctx);
1580     rv = do_sign_init(&mctx, pkey, md, sigopts);
1581     if (rv > 0)
1582         rv = X509_CRL_sign_ctx(x, &mctx);
1583     EVP_MD_CTX_cleanup(&mctx);
1584     return rv > 0 ? 1 : 0;
1585 }