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