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