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