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