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