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