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