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