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