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