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