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