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