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