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