59baa89bcf16cfb232b81e45f9975a148ee01892
[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 (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
521             BIO_printf(bio_err,
522                        "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
523                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
524                        OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
525
526         if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
527             BIO_printf(bio_err,
528                        "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
529                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
530                        OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
531
532         if (genctx == NULL) {
533             genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
534                                     &keyalgstr, gen_eng);
535             if (!genctx)
536                 goto end;
537         }
538
539         if (pkeyopts != NULL) {
540             char *genopt;
541             for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
542                 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
543                 if (pkey_ctrl_string(genctx, genopt) <= 0) {
544                     BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
545                     ERR_print_errors(bio_err);
546                     goto end;
547                 }
548             }
549         }
550
551         if (pkey_type == EVP_PKEY_EC) {
552             BIO_printf(bio_err, "Generating an EC private key\n");
553         } else {
554             BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
555                        newkey, keyalgstr);
556         }
557
558         EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
559         EVP_PKEY_CTX_set_app_data(genctx, bio_err);
560
561         if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
562             BIO_puts(bio_err, "Error Generating Key\n");
563             goto end;
564         }
565
566         EVP_PKEY_CTX_free(genctx);
567         genctx = NULL;
568
569         if (keyout == NULL) {
570             keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
571             if (keyout == NULL)
572                 ERR_clear_error();
573         }
574
575         if (keyout == NULL)
576             BIO_printf(bio_err, "writing new private key to stdout\n");
577         else
578             BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
579         out = bio_open_owner(keyout, outformat, private);
580         if (out == NULL)
581             goto end;
582
583         p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
584         if (p == NULL) {
585             ERR_clear_error();
586             p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
587             if (p == NULL)
588                 ERR_clear_error();
589         }
590         if ((p != NULL) && (strcmp(p, "no") == 0))
591             cipher = NULL;
592         if (nodes)
593             cipher = NULL;
594
595         i = 0;
596  loop:
597         assert(private);
598         if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
599                                       NULL, 0, NULL, passout)) {
600             if ((ERR_GET_REASON(ERR_peek_error()) ==
601                  PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
602                 ERR_clear_error();
603                 i++;
604                 goto loop;
605             }
606             goto end;
607         }
608         BIO_free(out);
609         out = NULL;
610         BIO_printf(bio_err, "-----\n");
611     }
612
613     if (!newreq) {
614         in = bio_open_default(infile, 'r', informat);
615         if (in == NULL)
616             goto end;
617
618         if (informat == FORMAT_ASN1)
619             req = d2i_X509_REQ_bio(in, NULL);
620         else
621             req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
622         if (req == NULL) {
623             BIO_printf(bio_err, "unable to load X509 request\n");
624             goto end;
625         }
626     }
627
628     if (newreq || x509) {
629         if (pkey == NULL) {
630             BIO_printf(bio_err, "you need to specify a private key\n");
631             goto end;
632         }
633
634         if (req == NULL) {
635             req = X509_REQ_new();
636             if (req == NULL) {
637                 goto end;
638             }
639
640             i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
641             subj = NULL;        /* done processing '-subj' option */
642             if (!i) {
643                 BIO_printf(bio_err, "problems making Certificate Request\n");
644                 goto end;
645             }
646         }
647         if (x509) {
648             EVP_PKEY *tmppkey;
649             X509V3_CTX ext_ctx;
650             if ((x509ss = X509_new()) == NULL)
651                 goto end;
652
653             /* Set version to V3 */
654             if ((extensions != NULL || addext_conf != NULL)
655                 && !X509_set_version(x509ss, 2))
656                 goto end;
657             if (serial != NULL) {
658                 if (!X509_set_serialNumber(x509ss, serial))
659                     goto end;
660             } else {
661                 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
662                     goto end;
663             }
664
665             if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
666                 goto end;
667             if (days == 0) {
668                 /* set default days if it's not specified */
669                 days = 30;
670             }
671             if (!set_cert_times(x509ss, NULL, NULL, days))
672                 goto end;
673             if (!X509_set_subject_name
674                 (x509ss, X509_REQ_get_subject_name(req)))
675                 goto end;
676             tmppkey = X509_REQ_get0_pubkey(req);
677             if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
678                 goto end;
679
680             /* Set up V3 context struct */
681
682             X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
683             X509V3_set_nconf(&ext_ctx, req_conf);
684
685             /* Add extensions */
686             if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
687                                                             &ext_ctx, extensions,
688                                                             x509ss)) {
689                 BIO_printf(bio_err, "Error Loading extension section %s\n",
690                            extensions);
691                 goto end;
692             }
693             if (addext_conf != NULL
694                 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
695                                          x509ss)) {
696                 BIO_printf(bio_err, "Error Loading command line extensions\n");
697                 goto end;
698             }
699
700             /* If a pre-cert was requested, we need to add a poison extension */
701             if (precert) {
702                 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
703                     != 1) {
704                     BIO_printf(bio_err, "Error adding poison extension\n");
705                     goto end;
706                 }
707             }
708
709             i = do_X509_sign(x509ss, pkey, digest, sigopts);
710             if (!i) {
711                 ERR_print_errors(bio_err);
712                 goto end;
713             }
714         } else {
715             X509V3_CTX ext_ctx;
716
717             /* Set up V3 context struct */
718
719             X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
720             X509V3_set_nconf(&ext_ctx, req_conf);
721
722             /* Add extensions */
723             if (req_exts != NULL
724                 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
725                                              req_exts, req)) {
726                 BIO_printf(bio_err, "Error Loading extension section %s\n",
727                            req_exts);
728                 goto end;
729             }
730             if (addext_conf != NULL
731                 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
732                                              req)) {
733                 BIO_printf(bio_err, "Error Loading command line extensions\n");
734                 goto end;
735             }
736             i = do_X509_REQ_sign(req, pkey, digest, sigopts);
737             if (!i) {
738                 ERR_print_errors(bio_err);
739                 goto end;
740             }
741         }
742     }
743
744     if (subj && x509) {
745         BIO_printf(bio_err, "Cannot modify certificate subject\n");
746         goto end;
747     }
748
749     if (subj && !x509) {
750         if (verbose) {
751             BIO_printf(bio_err, "Modifying Request's Subject\n");
752             print_name(bio_err, "old subject=",
753                        X509_REQ_get_subject_name(req), get_nameopt());
754         }
755
756         if (build_subject(req, subj, chtype, multirdn) == 0) {
757             BIO_printf(bio_err, "ERROR: cannot modify subject\n");
758             ret = 1;
759             goto end;
760         }
761
762         if (verbose) {
763             print_name(bio_err, "new subject=",
764                        X509_REQ_get_subject_name(req), get_nameopt());
765         }
766     }
767
768     if (verify && !x509) {
769         EVP_PKEY *tpubkey = pkey;
770
771         if (tpubkey == NULL) {
772             tpubkey = X509_REQ_get0_pubkey(req);
773             if (tpubkey == NULL)
774                 goto end;
775         }
776
777         i = X509_REQ_verify(req, tpubkey);
778
779         if (i < 0) {
780             goto end;
781         } else if (i == 0) {
782             BIO_printf(bio_err, "verify failure\n");
783             ERR_print_errors(bio_err);
784         } else {                 /* if (i > 0) */
785             BIO_printf(bio_err, "verify OK\n");
786         }
787     }
788
789     if (noout && !text && !modulus && !subject && !pubkey) {
790         ret = 0;
791         goto end;
792     }
793
794     out = bio_open_default(outfile,
795                            keyout != NULL && outfile != NULL &&
796                            strcmp(keyout, outfile) == 0 ? 'a' : 'w',
797                            outformat);
798     if (out == NULL)
799         goto end;
800
801     if (pubkey) {
802         EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
803
804         if (tpubkey == NULL) {
805             BIO_printf(bio_err, "Error getting public key\n");
806             ERR_print_errors(bio_err);
807             goto end;
808         }
809         PEM_write_bio_PUBKEY(out, tpubkey);
810     }
811
812     if (text) {
813         if (x509)
814             X509_print_ex(out, x509ss, get_nameopt(), reqflag);
815         else
816             X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
817     }
818
819     if (subject) {
820         if (x509)
821             print_name(out, "subject=", X509_get_subject_name(x509ss),
822                        get_nameopt());
823         else
824             print_name(out, "subject=", X509_REQ_get_subject_name(req),
825                        get_nameopt());
826     }
827
828     if (modulus) {
829         EVP_PKEY *tpubkey;
830
831         if (x509)
832             tpubkey = X509_get0_pubkey(x509ss);
833         else
834             tpubkey = X509_REQ_get0_pubkey(req);
835         if (tpubkey == NULL) {
836             fprintf(stdout, "Modulus=unavailable\n");
837             goto end;
838         }
839         fprintf(stdout, "Modulus=");
840 #ifndef OPENSSL_NO_RSA
841         if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
842             const BIGNUM *n;
843             RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
844             BN_print(out, n);
845         } else
846 #endif
847             fprintf(stdout, "Wrong Algorithm type");
848         fprintf(stdout, "\n");
849     }
850
851     if (!noout && !x509) {
852         if (outformat == FORMAT_ASN1)
853             i = i2d_X509_REQ_bio(out, req);
854         else if (newhdr)
855             i = PEM_write_bio_X509_REQ_NEW(out, req);
856         else
857             i = PEM_write_bio_X509_REQ(out, req);
858         if (!i) {
859             BIO_printf(bio_err, "unable to write X509 request\n");
860             goto end;
861         }
862     }
863     if (!noout && x509 && (x509ss != NULL)) {
864         if (outformat == FORMAT_ASN1)
865             i = i2d_X509_bio(out, x509ss);
866         else
867             i = PEM_write_bio_X509(out, x509ss);
868         if (!i) {
869             BIO_printf(bio_err, "unable to write X509 certificate\n");
870             goto end;
871         }
872     }
873     ret = 0;
874  end:
875     if (ret) {
876         ERR_print_errors(bio_err);
877     }
878     NCONF_free(req_conf);
879     BIO_free(addext_bio);
880     BIO_free(in);
881     BIO_free_all(out);
882     EVP_PKEY_free(pkey);
883     EVP_PKEY_CTX_free(genctx);
884     sk_OPENSSL_STRING_free(pkeyopts);
885     sk_OPENSSL_STRING_free(sigopts);
886 #ifndef OPENSSL_NO_ENGINE
887     ENGINE_free(gen_eng);
888 #endif
889     OPENSSL_free(keyalgstr);
890     X509_REQ_free(req);
891     X509_free(x509ss);
892     ASN1_INTEGER_free(serial);
893     release_engine(e);
894     if (passin != nofree_passin)
895         OPENSSL_free(passin);
896     if (passout != nofree_passout)
897         OPENSSL_free(passout);
898     return ret;
899 }
900
901 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
902                     int attribs, unsigned long chtype)
903 {
904     int ret = 0, i;
905     char no_prompt = 0;
906     STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
907     char *tmp, *dn_sect, *attr_sect;
908
909     tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
910     if (tmp == NULL)
911         ERR_clear_error();
912     if ((tmp != NULL) && strcmp(tmp, "no") == 0)
913         no_prompt = 1;
914
915     dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
916     if (dn_sect == NULL) {
917         BIO_printf(bio_err, "unable to find '%s' in config\n",
918                    DISTINGUISHED_NAME);
919         goto err;
920     }
921     dn_sk = NCONF_get_section(req_conf, dn_sect);
922     if (dn_sk == NULL) {
923         BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
924         goto err;
925     }
926
927     attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
928     if (attr_sect == NULL) {
929         ERR_clear_error();
930         attr_sk = NULL;
931     } else {
932         attr_sk = NCONF_get_section(req_conf, attr_sect);
933         if (attr_sk == NULL) {
934             BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
935             goto err;
936         }
937     }
938
939     /* setup version number */
940     if (!X509_REQ_set_version(req, 0L))
941         goto err;               /* version 1 */
942
943     if (subj)
944         i = build_subject(req, subj, chtype, multirdn);
945     else if (no_prompt)
946         i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
947     else
948         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
949                         chtype);
950     if (!i)
951         goto err;
952
953     if (!X509_REQ_set_pubkey(req, pkey))
954         goto err;
955
956     ret = 1;
957  err:
958     return ret;
959 }
960
961 /*
962  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
963  * where characters may be escaped by \
964  */
965 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
966                          int multirdn)
967 {
968     X509_NAME *n;
969
970     if ((n = parse_name(subject, chtype, multirdn)) == NULL)
971         return 0;
972
973     if (!X509_REQ_set_subject_name(req, n)) {
974         X509_NAME_free(n);
975         return 0;
976     }
977     X509_NAME_free(n);
978     return 1;
979 }
980
981 static int prompt_info(X509_REQ *req,
982                        STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
983                        STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
984                        int attribs, unsigned long chtype)
985 {
986     int i;
987     char *p, *q;
988     char buf[100];
989     int nid, mval;
990     long n_min, n_max;
991     char *type, *value;
992     const char *def;
993     CONF_VALUE *v;
994     X509_NAME *subj;
995     subj = X509_REQ_get_subject_name(req);
996
997     if (!batch) {
998         BIO_printf(bio_err,
999                    "You are about to be asked to enter information that will be incorporated\n");
1000         BIO_printf(bio_err, "into your certificate request.\n");
1001         BIO_printf(bio_err,
1002                    "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1003         BIO_printf(bio_err,
1004                    "There are quite a few fields but you can leave some blank\n");
1005         BIO_printf(bio_err,
1006                    "For some fields there will be a default value,\n");
1007         BIO_printf(bio_err,
1008                    "If you enter '.', the field will be left blank.\n");
1009         BIO_printf(bio_err, "-----\n");
1010     }
1011
1012     if (sk_CONF_VALUE_num(dn_sk)) {
1013         i = -1;
1014  start:
1015         for ( ; ; ) {
1016             i++;
1017             if (sk_CONF_VALUE_num(dn_sk) <= i)
1018                 break;
1019
1020             v = sk_CONF_VALUE_value(dn_sk, i);
1021             p = q = NULL;
1022             type = v->name;
1023             if (!check_end(type, "_min") || !check_end(type, "_max") ||
1024                 !check_end(type, "_default") || !check_end(type, "_value"))
1025                 continue;
1026             /*
1027              * Skip past any leading X. X: X, etc to allow for multiple
1028              * instances
1029              */
1030             for (p = v->name; *p; p++)
1031                 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1032                     p++;
1033                     if (*p)
1034                         type = p;
1035                     break;
1036                 }
1037             if (*type == '+') {
1038                 mval = -1;
1039                 type++;
1040             } else {
1041                 mval = 0;
1042             }
1043             /* If OBJ not recognised ignore it */
1044             if ((nid = OBJ_txt2nid(type)) == NID_undef)
1045                 goto start;
1046             if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1047                 return 0;
1048             if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1049                 ERR_clear_error();
1050                 def = "";
1051             }
1052
1053             if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1054                 return 0;
1055             if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1056                 ERR_clear_error();
1057                 value = NULL;
1058             }
1059
1060             if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1061                 return 0;
1062             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1063                 ERR_clear_error();
1064                 n_min = -1;
1065             }
1066
1067
1068             if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1069                 return 0;
1070             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1071                 ERR_clear_error();
1072                 n_max = -1;
1073             }
1074
1075             if (!add_DN_object(subj, v->value, def, value, nid,
1076                                n_min, n_max, chtype, mval))
1077                 return 0;
1078         }
1079         if (X509_NAME_entry_count(subj) == 0) {
1080             BIO_printf(bio_err,
1081                        "error, no objects specified in config file\n");
1082             return 0;
1083         }
1084
1085         if (attribs) {
1086             if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1087                 && (!batch)) {
1088                 BIO_printf(bio_err,
1089                            "\nPlease enter the following 'extra' attributes\n");
1090                 BIO_printf(bio_err,
1091                            "to be sent with your certificate request\n");
1092             }
1093
1094             i = -1;
1095  start2:
1096             for ( ; ; ) {
1097                 i++;
1098                 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1099                     break;
1100
1101                 v = sk_CONF_VALUE_value(attr_sk, i);
1102                 type = v->name;
1103                 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1104                     goto start2;
1105
1106                 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1107                     return 0;
1108                 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1109                     == NULL) {
1110                     ERR_clear_error();
1111                     def = "";
1112                 }
1113
1114                 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1115                     return 0;
1116                 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1117                     == NULL) {
1118                     ERR_clear_error();
1119                     value = NULL;
1120                 }
1121
1122                 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1123                     return 0;
1124                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1125                     ERR_clear_error();
1126                     n_min = -1;
1127                 }
1128
1129                 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1130                     return 0;
1131                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1132                     ERR_clear_error();
1133                     n_max = -1;
1134                 }
1135
1136                 if (!add_attribute_object(req,
1137                                           v->value, def, value, nid, n_min,
1138                                           n_max, chtype))
1139                     return 0;
1140             }
1141         }
1142     } else {
1143         BIO_printf(bio_err, "No template, please set one up.\n");
1144         return 0;
1145     }
1146
1147     return 1;
1148
1149 }
1150
1151 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1152                      STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1153                      unsigned long chtype)
1154 {
1155     int i, spec_char, plus_char;
1156     char *p, *q;
1157     char *type;
1158     CONF_VALUE *v;
1159     X509_NAME *subj;
1160
1161     subj = X509_REQ_get_subject_name(req);
1162
1163     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1164         int mval;
1165         v = sk_CONF_VALUE_value(dn_sk, i);
1166         p = q = NULL;
1167         type = v->name;
1168         /*
1169          * Skip past any leading X. X: X, etc to allow for multiple instances
1170          */
1171         for (p = v->name; *p; p++) {
1172 #ifndef CHARSET_EBCDIC
1173             spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1174 #else
1175             spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1176                     || (*p == os_toascii['.']));
1177 #endif
1178             if (spec_char) {
1179                 p++;
1180                 if (*p)
1181                     type = p;
1182                 break;
1183             }
1184         }
1185 #ifndef CHARSET_EBCDIC
1186         plus_char = (*type == '+');
1187 #else
1188         plus_char = (*type == os_toascii['+']);
1189 #endif
1190         if (plus_char) {
1191             type++;
1192             mval = -1;
1193         } else {
1194             mval = 0;
1195         }
1196         if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1197                                         (unsigned char *)v->value, -1, -1,
1198                                         mval))
1199             return 0;
1200
1201     }
1202
1203     if (!X509_NAME_entry_count(subj)) {
1204         BIO_printf(bio_err, "error, no objects specified in config file\n");
1205         return 0;
1206     }
1207     if (attribs) {
1208         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1209             v = sk_CONF_VALUE_value(attr_sk, i);
1210             if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1211                                            (unsigned char *)v->value, -1))
1212                 return 0;
1213         }
1214     }
1215     return 1;
1216 }
1217
1218 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1219                          char *value, int nid, int n_min, int n_max,
1220                          unsigned long chtype, int mval)
1221 {
1222     int ret = 0;
1223     char buf[1024];
1224
1225     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1226                      "DN value", "DN default");
1227     if ((ret == 0) || (ret == 1))
1228         return ret;
1229     ret = 1;
1230
1231     if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1232                                     (unsigned char *)buf, -1, -1, mval))
1233         ret = 0;
1234
1235     return ret;
1236 }
1237
1238 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1239                                 char *value, int nid, int n_min,
1240                                 int n_max, unsigned long chtype)
1241 {
1242     int ret = 0;
1243     char buf[1024];
1244
1245     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1246                      "Attribute value", "Attribute default");
1247     if ((ret == 0) || (ret == 1))
1248         return ret;
1249     ret = 1;
1250
1251     if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1252                                    (unsigned char *)buf, -1)) {
1253         BIO_printf(bio_err, "Error adding attribute\n");
1254         ERR_print_errors(bio_err);
1255         ret = 0;
1256     }
1257
1258     return ret;
1259 }
1260
1261
1262 static int build_data(char *text, const char *def,
1263                          char *value, int n_min, int n_max,
1264                          char *buf, const int buf_size,
1265                          const char *desc1, const char *desc2
1266                          )
1267 {
1268     int i;
1269  start:
1270     if (!batch)
1271         BIO_printf(bio_err, "%s [%s]:", text, def);
1272     (void)BIO_flush(bio_err);
1273     if (value != NULL) {
1274         if (!join(buf, buf_size, value, "\n", desc1))
1275             return 0;
1276         BIO_printf(bio_err, "%s\n", value);
1277     } else {
1278         buf[0] = '\0';
1279         if (!batch) {
1280             if (!fgets(buf, buf_size, stdin))
1281                 return 0;
1282         } else {
1283             buf[0] = '\n';
1284             buf[1] = '\0';
1285         }
1286     }
1287
1288     if (buf[0] == '\0')
1289         return 0;
1290     if (buf[0] == '\n') {
1291         if ((def == NULL) || (def[0] == '\0'))
1292             return 1;
1293         if (!join(buf, buf_size, def, "\n", desc2))
1294             return 0;
1295     } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1296         return 1;
1297     }
1298
1299     i = strlen(buf);
1300     if (buf[i - 1] != '\n') {
1301         BIO_printf(bio_err, "weird input :-(\n");
1302         return 0;
1303     }
1304     buf[--i] = '\0';
1305 #ifdef CHARSET_EBCDIC
1306     ebcdic2ascii(buf, buf, i);
1307 #endif
1308     if (!req_check_len(i, n_min, n_max)) {
1309         if (batch || value)
1310             return 0;
1311         goto start;
1312     }
1313     return 2;
1314 }
1315
1316 static int req_check_len(int len, int n_min, int n_max)
1317 {
1318     if ((n_min > 0) && (len < n_min)) {
1319         BIO_printf(bio_err,
1320                    "string is too short, it needs to be at least %d bytes long\n",
1321                    n_min);
1322         return 0;
1323     }
1324     if ((n_max >= 0) && (len > n_max)) {
1325         BIO_printf(bio_err,
1326                    "string is too long, it needs to be no more than %d bytes long\n",
1327                    n_max);
1328         return 0;
1329     }
1330     return 1;
1331 }
1332
1333 /* Check if the end of a string matches 'end' */
1334 static int check_end(const char *str, const char *end)
1335 {
1336     size_t elen, slen;
1337     const char *tmp;
1338
1339     elen = strlen(end);
1340     slen = strlen(str);
1341     if (elen > slen)
1342         return 1;
1343     tmp = str + slen - elen;
1344     return strcmp(tmp, end);
1345 }
1346
1347 /*
1348  * Merge the two strings together into the result buffer checking for
1349  * overflow and producing an error message if there is.
1350  */
1351 static int join(char buf[], size_t buf_size, const char *name,
1352                 const char *tail, const char *desc)
1353 {
1354     const size_t name_len = strlen(name), tail_len = strlen(tail);
1355
1356     if (name_len + tail_len + 1 > buf_size) {
1357         BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1358         return 0;
1359     }
1360     memcpy(buf, name, name_len);
1361     memcpy(buf + name_len, tail, tail_len + 1);
1362     return 1;
1363 }
1364
1365 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1366                                     int *pkey_type, long *pkeylen,
1367                                     char **palgnam, ENGINE *keygen_engine)
1368 {
1369     EVP_PKEY_CTX *gctx = NULL;
1370     EVP_PKEY *param = NULL;
1371     long keylen = -1;
1372     BIO *pbio = NULL;
1373     const char *paramfile = NULL;
1374
1375     if (gstr == NULL) {
1376         *pkey_type = EVP_PKEY_RSA;
1377         keylen = *pkeylen;
1378     } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1379         *pkey_type = EVP_PKEY_RSA;
1380         keylen = atol(gstr);
1381         *pkeylen = keylen;
1382     } else if (strncmp(gstr, "param:", 6) == 0) {
1383         paramfile = gstr + 6;
1384     } else {
1385         const char *p = strchr(gstr, ':');
1386         int len;
1387         ENGINE *tmpeng;
1388         const EVP_PKEY_ASN1_METHOD *ameth;
1389
1390         if (p != NULL)
1391             len = p - gstr;
1392         else
1393             len = strlen(gstr);
1394         /*
1395          * The lookup of a the string will cover all engines so keep a note
1396          * of the implementation.
1397          */
1398
1399         ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1400
1401         if (ameth == NULL) {
1402             BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1403             return NULL;
1404         }
1405
1406         EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1407 #ifndef OPENSSL_NO_ENGINE
1408         ENGINE_finish(tmpeng);
1409 #endif
1410         if (*pkey_type == EVP_PKEY_RSA) {
1411             if (p != NULL) {
1412                 keylen = atol(p + 1);
1413                 *pkeylen = keylen;
1414             } else {
1415                 keylen = *pkeylen;
1416             }
1417         } else if (p != NULL) {
1418             paramfile = p + 1;
1419         }
1420     }
1421
1422     if (paramfile != NULL) {
1423         pbio = BIO_new_file(paramfile, "r");
1424         if (pbio == NULL) {
1425             BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1426             return NULL;
1427         }
1428         param = PEM_read_bio_Parameters(pbio, NULL);
1429
1430         if (param == NULL) {
1431             X509 *x;
1432
1433             (void)BIO_reset(pbio);
1434             x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1435             if (x != NULL) {
1436                 param = X509_get_pubkey(x);
1437                 X509_free(x);
1438             }
1439         }
1440
1441         BIO_free(pbio);
1442
1443         if (param == NULL) {
1444             BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1445             return NULL;
1446         }
1447         if (*pkey_type == -1) {
1448             *pkey_type = EVP_PKEY_id(param);
1449         } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1450             BIO_printf(bio_err, "Key Type does not match parameters\n");
1451             EVP_PKEY_free(param);
1452             return NULL;
1453         }
1454     }
1455
1456     if (palgnam != NULL) {
1457         const EVP_PKEY_ASN1_METHOD *ameth;
1458         ENGINE *tmpeng;
1459         const char *anam;
1460
1461         ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1462         if (ameth == NULL) {
1463             BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1464             return NULL;
1465         }
1466         EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1467         *palgnam = OPENSSL_strdup(anam);
1468 #ifndef OPENSSL_NO_ENGINE
1469         ENGINE_finish(tmpeng);
1470 #endif
1471     }
1472
1473     if (param != NULL) {
1474         gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1475         *pkeylen = EVP_PKEY_bits(param);
1476         EVP_PKEY_free(param);
1477     } else {
1478         gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1479     }
1480
1481     if (gctx == NULL) {
1482         BIO_puts(bio_err, "Error allocating keygen context\n");
1483         ERR_print_errors(bio_err);
1484         return NULL;
1485     }
1486
1487     if (EVP_PKEY_keygen_init(gctx) <= 0) {
1488         BIO_puts(bio_err, "Error initializing keygen context\n");
1489         ERR_print_errors(bio_err);
1490         EVP_PKEY_CTX_free(gctx);
1491         return NULL;
1492     }
1493 #ifndef OPENSSL_NO_RSA
1494     if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1495         if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1496             BIO_puts(bio_err, "Error setting RSA keysize\n");
1497             ERR_print_errors(bio_err);
1498             EVP_PKEY_CTX_free(gctx);
1499             return NULL;
1500         }
1501     }
1502 #endif
1503
1504     return gctx;
1505 }
1506
1507 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1508 {
1509     char c = '*';
1510     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1511     int p;
1512     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1513     if (p == 0)
1514         c = '.';
1515     if (p == 1)
1516         c = '+';
1517     if (p == 2)
1518         c = '*';
1519     if (p == 3)
1520         c = '\n';
1521     BIO_write(b, &c, 1);
1522     (void)BIO_flush(b);
1523     return 1;
1524 }
1525
1526 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1527                         const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1528 {
1529     EVP_PKEY_CTX *pkctx = NULL;
1530     int i;
1531
1532     if (ctx == NULL)
1533         return 0;
1534     if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1535         return 0;
1536     for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1537         char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1538         if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1539             BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1540             ERR_print_errors(bio_err);
1541             return 0;
1542         }
1543     }
1544     return 1;
1545 }
1546
1547 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1548                  STACK_OF(OPENSSL_STRING) *sigopts)
1549 {
1550     int rv;
1551     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1552
1553     rv = do_sign_init(mctx, pkey, md, sigopts);
1554     if (rv > 0)
1555         rv = X509_sign_ctx(x, mctx);
1556     EVP_MD_CTX_free(mctx);
1557     return rv > 0 ? 1 : 0;
1558 }
1559
1560 int do_X509_REQ_sign(X509_REQ *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_REQ_sign_ctx(x, mctx);
1568     EVP_MD_CTX_free(mctx);
1569     return rv > 0 ? 1 : 0;
1570 }
1571
1572 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1573                      STACK_OF(OPENSSL_STRING) *sigopts)
1574 {
1575     int rv;
1576     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1577     rv = do_sign_init(mctx, pkey, md, sigopts);
1578     if (rv > 0)
1579         rv = X509_CRL_sign_ctx(x, mctx);
1580     EVP_MD_CTX_free(mctx);
1581     return rv > 0 ? 1 : 0;
1582 }