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