Fix provider cipher reinit after init/update with a partial update block.
[openssl.git] / apps / req.c
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
12
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <time.h>
16 #include <string.h>
17 #include <ctype.h>
18 #include "apps.h"
19 #include "progs.h"
20 #include <openssl/bio.h>
21 #include <openssl/evp.h>
22 #include <openssl/conf.h>
23 #include <openssl/err.h>
24 #include <openssl/asn1.h>
25 #include <openssl/x509.h>
26 #include <openssl/x509v3.h>
27 #include <openssl/objects.h>
28 #include <openssl/pem.h>
29 #include <openssl/bn.h>
30 #include <openssl/lhash.h>
31 #ifndef OPENSSL_NO_RSA
32 # include <openssl/rsa.h>
33 #endif
34 #ifndef OPENSSL_NO_DSA
35 # include <openssl/dsa.h>
36 #endif
37
38 DEFINE_STACK_OF(CONF_VALUE)
39 DEFINE_STACK_OF_STRING()
40
41 #define BITS            "default_bits"
42 #define KEYFILE         "default_keyfile"
43 #define PROMPT          "prompt"
44 #define DISTINGUISHED_NAME      "distinguished_name"
45 #define ATTRIBUTES      "attributes"
46 #define V3_EXTENSIONS   "x509_extensions"
47 #define REQ_EXTENSIONS  "req_extensions"
48 #define STRING_MASK     "string_mask"
49 #define UTF8_IN         "utf8"
50
51 #define DEFAULT_KEY_LENGTH      2048
52 #define MIN_KEY_LENGTH          512
53
54 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
55                     int attribs, unsigned long chtype);
56 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
57                          int multirdn);
58 static int prompt_info(X509_REQ *req,
59                        STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
60                        STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
61                        int attribs, unsigned long chtype);
62 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
63                      STACK_OF(CONF_VALUE) *attr, int attribs,
64                      unsigned long chtype);
65 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
66                                 char *value, int nid, int n_min, int n_max,
67                                 unsigned long chtype);
68 static int add_DN_object(X509_NAME *n, char *text, const char *def,
69                          char *value, int nid, int n_min, int n_max,
70                          unsigned long chtype, int mval);
71 static int genpkey_cb(EVP_PKEY_CTX *ctx);
72 static int build_data(char *text, const char *def,
73                       char *value, int n_min, int n_max,
74                       char *buf, const int buf_size,
75                       const char *desc1, const char *desc2
76                       );
77 static int req_check_len(int len, int n_min, int n_max);
78 static int check_end(const char *str, const char *end);
79 static int join(char buf[], size_t buf_size, const char *name,
80                 const char *tail, const char *desc);
81 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
82                                     int *pkey_type, long *pkeylen,
83                                     char **palgnam, ENGINE *keygen_engine);
84
85 static const char *section = "req";
86 static CONF *req_conf = NULL;
87 static CONF *addext_conf = NULL;
88 static int batch = 0;
89
90 typedef enum OPTION_choice {
91     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
92     OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
93     OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
94     OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
95     OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
96     OPT_VERIFY, OPT_NOENC, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
97     OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
98     OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
99     OPT_REQEXTS, OPT_PRECERT, OPT_MD,
100     OPT_SECTION,
101     OPT_R_ENUM, OPT_PROV_ENUM
102 } OPTION_CHOICE;
103
104 const OPTIONS req_options[] = {
105     OPT_SECTION("General"),
106     {"help", OPT_HELP, '-', "Display this summary"},
107 #ifndef OPENSSL_NO_ENGINE
108     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
109     {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
110      "Specify engine to be used for key generation operations"},
111 #endif
112     {"in", OPT_IN, '<', "Input file"},
113     {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
114     {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
115
116     OPT_SECTION("Certificate"),
117     {"new", OPT_NEW, '-', "New request"},
118     {"config", OPT_CONFIG, '<', "Request template file"},
119     {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
120     {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
121     {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
122     {"reqopt", OPT_REQOPT, 's', "Various request text options"},
123     {"text", OPT_TEXT, '-', "Text form of request"},
124     {"x509", OPT_X509, '-',
125      "Output an x509 structure instead of a cert request"},
126     {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
127     {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
128     {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
129     {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
130      "Enable support for multivalued RDNs"},
131     {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
132     {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
133     {"addext", OPT_ADDEXT, 's',
134      "Additional cert extension key=value pair (may be given more than once)"},
135     {"extensions", OPT_EXTENSIONS, 's',
136      "Cert extension section (override value in config file)"},
137     {"reqexts", OPT_REQEXTS, 's',
138      "Request extension section (override value in config file)"},
139     {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
140
141     OPT_SECTION("Keys and Signing"),
142     {"key", OPT_KEY, 's', "Private key to use"},
143     {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
144     {"pubkey", OPT_PUBKEY, '-', "Output public key"},
145     {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
146     {"passin", OPT_PASSIN, 's', "Private key password source"},
147     {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
148     {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
149     {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
150     {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
151     {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
152     {"", OPT_MD, '-', "Any supported digest"},
153
154     OPT_SECTION("Output"),
155     {"out", OPT_OUT, '>', "Output file"},
156     {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
157     {"batch", OPT_BATCH, '-',
158      "Do not ask anything during request generation"},
159     {"verbose", OPT_VERBOSE, '-', "Verbose output"},
160     {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
161     {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
162     {"noout", OPT_NOOUT, '-', "Do not output REQ"},
163     {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
164     {"modulus", OPT_MODULUS, '-', "RSA modulus"},
165
166     OPT_R_OPTIONS,
167     OPT_PROV_OPTIONS,
168     {NULL}
169 };
170
171
172 /*
173  * An LHASH of strings, where each string is an extension name.
174  */
175 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
176 {
177     return OPENSSL_LH_strhash((const char *)a);
178 }
179
180 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
181 {
182     return strcmp((const char *)a, (const char *)b);
183 }
184
185 static void exts_cleanup(OPENSSL_STRING *x)
186 {
187     OPENSSL_free((char *)x);
188 }
189
190 /*
191  * Is the |kv| key already duplicated?  This is remarkably tricky to get
192  * right.  Return 0 if unique, -1 on runtime error; 1 if found or a syntax
193  * error.
194  */
195 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
196 {
197     char *p;
198     size_t off;
199
200     /* Check syntax. */
201     /* Skip leading whitespace, make a copy. */
202     while (*kv && isspace(*kv))
203         if (*++kv == '\0')
204             return 1;
205     if ((p = strchr(kv, '=')) == NULL)
206         return 1;
207     off = p - kv;
208     if ((kv = OPENSSL_strdup(kv)) == NULL)
209         return -1;
210
211     /* Skip trailing space before the equal sign. */
212     for (p = kv + off; p > kv; --p)
213         if (!isspace(p[-1]))
214             break;
215     if (p == kv) {
216         OPENSSL_free(kv);
217         return 1;
218     }
219     *p = '\0';
220
221     /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
222     p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING*)kv);
223     if (p != NULL) {
224         OPENSSL_free(p);
225         return 1;
226     } else if (lh_OPENSSL_STRING_error(addexts)) {
227         OPENSSL_free(kv);
228         return -1;
229     }
230
231     return 0;
232 }
233
234 int req_main(int argc, char **argv)
235 {
236     ASN1_INTEGER *serial = NULL;
237     BIO *out = NULL;
238     ENGINE *e = NULL, *gen_eng = NULL;
239     EVP_PKEY *pkey = NULL;
240     EVP_PKEY_CTX *genctx = NULL;
241     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL;
242     LHASH_OF(OPENSSL_STRING) *addexts = NULL;
243     X509 *x509ss = NULL;
244     X509_REQ *req = NULL;
245     const EVP_CIPHER *cipher = NULL;
246     const EVP_MD *md_alg = NULL, *digest = NULL;
247     BIO *addext_bio = NULL;
248     char *extensions = NULL, *infile = NULL;
249     char *outfile = NULL, *keyfile = NULL;
250     char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
251     char *passin = NULL, *passout = NULL;
252     char *nofree_passin = NULL, *nofree_passout = NULL;
253     char *req_exts = NULL, *subj = NULL;
254     char *template = default_config_file, *keyout = NULL;
255     const char *keyalg = NULL;
256     OPTION_CHOICE o;
257     int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
258     int pkey_type = -1, private = 0;
259     int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
260     int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
261     int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
262     long newkey = -1;
263     unsigned long chtype = MBSTRING_ASC, reqflag = 0;
264
265 #ifndef OPENSSL_NO_DES
266     cipher = EVP_des_ede3_cbc();
267 #endif
268
269     prog = opt_init(argc, argv, req_options);
270     while ((o = opt_next()) != OPT_EOF) {
271         switch (o) {
272         case OPT_EOF:
273         case OPT_ERR:
274  opthelp:
275             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
276             goto end;
277         case OPT_HELP:
278             opt_help(req_options);
279             ret = 0;
280             goto end;
281         case OPT_INFORM:
282             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
283                 goto opthelp;
284             break;
285         case OPT_OUTFORM:
286             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
287                 goto opthelp;
288             break;
289         case OPT_ENGINE:
290             e = setup_engine(opt_arg(), 0);
291             break;
292         case OPT_KEYGEN_ENGINE:
293 #ifndef OPENSSL_NO_ENGINE
294             gen_eng = ENGINE_by_id(opt_arg());
295             if (gen_eng == NULL) {
296                 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
297                 goto opthelp;
298             }
299 #endif
300             break;
301         case OPT_KEY:
302             keyfile = opt_arg();
303             break;
304         case OPT_PUBKEY:
305             pubkey = 1;
306             break;
307         case OPT_NEW:
308             newreq = 1;
309             break;
310         case OPT_CONFIG:
311             template = opt_arg();
312             break;
313         case OPT_SECTION:
314             section = opt_arg();
315             break;
316         case OPT_KEYFORM:
317             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
318                 goto opthelp;
319             break;
320         case OPT_IN:
321             infile = opt_arg();
322             break;
323         case OPT_OUT:
324             outfile = opt_arg();
325             break;
326         case OPT_KEYOUT:
327             keyout = opt_arg();
328             break;
329         case OPT_PASSIN:
330             passargin = opt_arg();
331             break;
332         case OPT_PASSOUT:
333             passargout = opt_arg();
334             break;
335         case OPT_R_CASES:
336             if (!opt_rand(o))
337                 goto end;
338             break;
339         case OPT_PROV_CASES:
340             if (!opt_provider(o))
341                 goto end;
342             break;
343         case OPT_NEWKEY:
344             keyalg = opt_arg();
345             newreq = 1;
346             break;
347         case OPT_PKEYOPT:
348             if (pkeyopts == NULL)
349                 pkeyopts = sk_OPENSSL_STRING_new_null();
350             if (pkeyopts == NULL
351                     || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
352                 goto opthelp;
353             break;
354         case OPT_SIGOPT:
355             if (!sigopts)
356                 sigopts = sk_OPENSSL_STRING_new_null();
357             if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
358                 goto opthelp;
359             break;
360         case OPT_VFYOPT:
361             if (!vfyopts)
362                 vfyopts = sk_OPENSSL_STRING_new_null();
363             if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
364                 goto opthelp;
365             break;
366         case OPT_BATCH:
367             batch = 1;
368             break;
369         case OPT_NEWHDR:
370             newhdr = 1;
371             break;
372         case OPT_MODULUS:
373             modulus = 1;
374             break;
375         case OPT_VERIFY:
376             verify = 1;
377             break;
378         case OPT_NODES:
379         case OPT_NOENC:
380             noenc = 1;
381             break;
382         case OPT_NOOUT:
383             noout = 1;
384             break;
385         case OPT_VERBOSE:
386             verbose = 1;
387             break;
388         case OPT_UTF8:
389             chtype = MBSTRING_UTF8;
390             break;
391         case OPT_NAMEOPT:
392             if (!set_nameopt(opt_arg()))
393                 goto opthelp;
394             break;
395         case OPT_REQOPT:
396             if (!set_cert_ex(&reqflag, opt_arg()))
397                 goto opthelp;
398             break;
399         case OPT_TEXT:
400             text = 1;
401             break;
402         case OPT_X509:
403             x509 = 1;
404             break;
405         case OPT_DAYS:
406             days = atoi(opt_arg());
407             break;
408         case OPT_SET_SERIAL:
409             if (serial != NULL) {
410                 BIO_printf(bio_err, "Serial number supplied twice\n");
411                 goto opthelp;
412             }
413             serial = s2i_ASN1_INTEGER(NULL, opt_arg());
414             if (serial == NULL)
415                 goto opthelp;
416             break;
417         case OPT_SUBJECT:
418             subject = 1;
419             break;
420         case OPT_SUBJ:
421             subj = opt_arg();
422             break;
423         case OPT_MULTIVALUE_RDN:
424             multirdn = 1;
425             break;
426         case OPT_ADDEXT:
427             p = opt_arg();
428             if (addexts == NULL) {
429                 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
430                 addext_bio = BIO_new(BIO_s_mem());
431                 if (addexts == NULL || addext_bio == NULL)
432                     goto end;
433             }
434             i = duplicated(addexts, p);
435             if (i == 1)
436                 goto opthelp;
437             if (i < 0 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
438                 goto end;
439             break;
440         case OPT_EXTENSIONS:
441             extensions = opt_arg();
442             break;
443         case OPT_REQEXTS:
444             req_exts = opt_arg();
445             break;
446         case OPT_PRECERT:
447             newreq = precert = 1;
448             break;
449         case OPT_MD:
450             if (!opt_md(opt_unknown(), &md_alg))
451                 goto opthelp;
452             digest = md_alg;
453             break;
454         }
455     }
456     argc = opt_num_rest();
457     if (argc != 0)
458         goto opthelp;
459
460     if (days && !x509)
461         BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
462     if (x509 && infile == NULL)
463         newreq = 1;
464
465     /* TODO: simplify this as pkey is still always NULL here */
466     private = newreq && (pkey == NULL) ? 1 : 0;
467
468     if (!app_passwd(passargin, passargout, &passin, &passout)) {
469         BIO_printf(bio_err, "Error getting passwords\n");
470         goto end;
471     }
472
473     if (verbose)
474         BIO_printf(bio_err, "Using configuration from %s\n", template);
475     if ((req_conf = app_load_config(template)) == NULL)
476         goto end;
477     if (addext_bio != NULL) {
478         if (verbose)
479             BIO_printf(bio_err,
480                        "Using additional configuration from command line\n");
481         if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
482             goto end;
483     }
484     if (template != default_config_file && !app_load_modules(req_conf))
485         goto end;
486
487     if (req_conf != NULL) {
488         p = NCONF_get_string(req_conf, NULL, "oid_file");
489         if (p == NULL)
490             ERR_clear_error();
491         if (p != NULL) {
492             BIO *oid_bio;
493
494             oid_bio = BIO_new_file(p, "r");
495             if (oid_bio == NULL) {
496                 /*-
497                 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
498                 ERR_print_errors(bio_err);
499                 */
500             } else {
501                 OBJ_create_objects(oid_bio);
502                 BIO_free(oid_bio);
503             }
504         }
505     }
506     if (!add_oid_section(req_conf))
507         goto end;
508
509     if (md_alg == NULL) {
510         p = NCONF_get_string(req_conf, section, "default_md");
511         if (p == NULL) {
512             ERR_clear_error();
513         } else {
514             if (!opt_md(p, &md_alg))
515                 goto opthelp;
516             digest = md_alg;
517         }
518     }
519
520     if (extensions == NULL) {
521         extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
522         if (extensions == NULL)
523             ERR_clear_error();
524     }
525     if (extensions != NULL) {
526         /* Check syntax of file */
527         X509V3_CTX ctx;
528         X509V3_set_ctx_test(&ctx);
529         X509V3_set_nconf(&ctx, req_conf);
530         if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
531             BIO_printf(bio_err,
532                        "Error Loading extension section %s\n", extensions);
533             goto end;
534         }
535     }
536     if (addext_conf != NULL) {
537         /* Check syntax of command line extensions */
538         X509V3_CTX ctx;
539         X509V3_set_ctx_test(&ctx);
540         X509V3_set_nconf(&ctx, addext_conf);
541         if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
542             BIO_printf(bio_err, "Error Loading command line extensions\n");
543             goto end;
544         }
545     }
546
547     if (passin == NULL) {
548         passin = nofree_passin =
549             NCONF_get_string(req_conf, section, "input_password");
550         if (passin == NULL)
551             ERR_clear_error();
552     }
553
554     if (passout == NULL) {
555         passout = nofree_passout =
556             NCONF_get_string(req_conf, section, "output_password");
557         if (passout == NULL)
558             ERR_clear_error();
559     }
560
561     p = NCONF_get_string(req_conf, section, STRING_MASK);
562     if (p == NULL)
563         ERR_clear_error();
564
565     if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
566         BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
567         goto end;
568     }
569
570     if (chtype != MBSTRING_UTF8) {
571         p = NCONF_get_string(req_conf, section, UTF8_IN);
572         if (p == NULL)
573             ERR_clear_error();
574         else if (strcmp(p, "yes") == 0)
575             chtype = MBSTRING_UTF8;
576     }
577
578     if (req_exts == NULL) {
579         req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
580         if (req_exts == NULL)
581             ERR_clear_error();
582     }
583     if (req_exts != NULL) {
584         /* Check syntax of file */
585         X509V3_CTX ctx;
586         X509V3_set_ctx_test(&ctx);
587         X509V3_set_nconf(&ctx, req_conf);
588         if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
589             BIO_printf(bio_err,
590                        "Error Loading request extension section %s\n",
591                        req_exts);
592             goto end;
593         }
594     }
595
596     if (keyfile != NULL) {
597         pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
598         if (pkey == NULL)
599             goto end;
600         app_RAND_load_conf(req_conf, section);
601     }
602
603     if (newreq && (pkey == NULL)) {
604         app_RAND_load_conf(req_conf, section);
605
606         if (!NCONF_get_number(req_conf, section, BITS, &newkey)) {
607             newkey = DEFAULT_KEY_LENGTH;
608         }
609
610         if (keyalg != NULL) {
611             genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
612                                     &keyalgstr, gen_eng);
613             if (genctx == NULL)
614                 goto end;
615         }
616
617         if (newkey < MIN_KEY_LENGTH
618             && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
619             BIO_printf(bio_err, "private key length is too short,\n");
620             BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
621                        MIN_KEY_LENGTH, newkey);
622             goto end;
623         }
624
625         if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
626             BIO_printf(bio_err,
627                        "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
628                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
629                        OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
630
631 #ifndef OPENSSL_NO_DSA
632         if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
633             BIO_printf(bio_err,
634                        "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
635                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
636                        OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
637 #endif
638
639         if (genctx == NULL) {
640             genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
641                                     &keyalgstr, gen_eng);
642             if (!genctx)
643                 goto end;
644         }
645
646         if (pkeyopts != NULL) {
647             char *genopt;
648             for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
649                 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
650                 if (pkey_ctrl_string(genctx, genopt) <= 0) {
651                     BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
652                     ERR_print_errors(bio_err);
653                     goto end;
654                 }
655             }
656         }
657
658         if (pkey_type == EVP_PKEY_EC) {
659             BIO_printf(bio_err, "Generating an EC private key\n");
660         } else {
661             BIO_printf(bio_err, "Generating a %s private key\n", keyalgstr);
662         }
663
664         EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
665         EVP_PKEY_CTX_set_app_data(genctx, bio_err);
666
667         if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
668             BIO_puts(bio_err, "Error Generating Key\n");
669             goto end;
670         }
671
672         EVP_PKEY_CTX_free(genctx);
673         genctx = NULL;
674
675         if (keyout == NULL) {
676             keyout = NCONF_get_string(req_conf, section, KEYFILE);
677             if (keyout == NULL)
678                 ERR_clear_error();
679         }
680
681         if (keyout == NULL)
682             BIO_printf(bio_err, "writing new private key to stdout\n");
683         else
684             BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
685         out = bio_open_owner(keyout, outformat, private);
686         if (out == NULL)
687             goto end;
688
689         p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
690         if (p == NULL) {
691             ERR_clear_error();
692             p = NCONF_get_string(req_conf, section, "encrypt_key");
693             if (p == NULL)
694                 ERR_clear_error();
695         }
696         if ((p != NULL) && (strcmp(p, "no") == 0))
697             cipher = NULL;
698         if (noenc)
699             cipher = NULL;
700
701         i = 0;
702  loop:
703         assert(private);
704         if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
705                                       NULL, 0, NULL, passout)) {
706             if ((ERR_GET_REASON(ERR_peek_error()) ==
707                  PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
708                 ERR_clear_error();
709                 i++;
710                 goto loop;
711             }
712             goto end;
713         }
714         BIO_free(out);
715         out = NULL;
716         BIO_printf(bio_err, "-----\n");
717     }
718
719     if (!newreq) {
720         req = load_csr(infile, informat, "X509 request");
721         if (req == NULL)
722             goto end;
723     }
724
725     if (newreq || x509) {
726         if (pkey == NULL) {
727             BIO_printf(bio_err, "you need to specify a private key\n");
728             goto end;
729         }
730
731         if (req == NULL) {
732             req = X509_REQ_new();
733             if (req == NULL) {
734                 goto end;
735             }
736
737             i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
738             subj = NULL;        /* done processing '-subj' option */
739             if (!i) {
740                 BIO_printf(bio_err, "problems making Certificate Request\n");
741                 goto end;
742             }
743         }
744         if (x509) {
745             EVP_PKEY *tmppkey;
746             X509V3_CTX ext_ctx;
747             if ((x509ss = X509_new_with_libctx(app_get0_libctx(),
748                                                app_get0_propq())) == NULL)
749                 goto end;
750
751             /* Set version to V3 */
752             if ((extensions != NULL || addext_conf != NULL)
753                 && !X509_set_version(x509ss, 2))
754                 goto end;
755             if (serial != NULL) {
756                 if (!X509_set_serialNumber(x509ss, serial))
757                     goto end;
758             } else {
759                 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
760                     goto end;
761             }
762
763             if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
764                 goto end;
765             if (days == 0) {
766                 /* set default days if it's not specified */
767                 days = 30;
768             }
769             if (!set_cert_times(x509ss, NULL, NULL, days))
770                 goto end;
771             if (!X509_set_subject_name
772                 (x509ss, X509_REQ_get_subject_name(req)))
773                 goto end;
774             tmppkey = X509_REQ_get0_pubkey(req);
775             if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
776                 goto end;
777
778             /* Set up V3 context struct */
779
780             X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
781             X509V3_set_nconf(&ext_ctx, req_conf);
782
783             /* Add extensions */
784             if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
785                                                             &ext_ctx, extensions,
786                                                             x509ss)) {
787                 BIO_printf(bio_err, "Error Loading extension section %s\n",
788                            extensions);
789                 goto end;
790             }
791             if (addext_conf != NULL
792                 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
793                                          x509ss)) {
794                 BIO_printf(bio_err, "Error Loading command line extensions\n");
795                 goto end;
796             }
797
798             /* If a pre-cert was requested, we need to add a poison extension */
799             if (precert) {
800                 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
801                     != 1) {
802                     BIO_printf(bio_err, "Error adding poison extension\n");
803                     goto end;
804                 }
805             }
806
807             i = do_X509_sign(x509ss, pkey, digest, sigopts);
808             if (!i) {
809                 ERR_print_errors(bio_err);
810                 goto end;
811             }
812         } else {
813             X509V3_CTX ext_ctx;
814
815             /* Set up V3 context struct */
816
817             X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
818             X509V3_set_nconf(&ext_ctx, req_conf);
819
820             /* Add extensions */
821             if (req_exts != NULL
822                 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
823                                              req_exts, req)) {
824                 BIO_printf(bio_err, "Error Loading extension section %s\n",
825                            req_exts);
826                 goto end;
827             }
828             if (addext_conf != NULL
829                 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
830                                              req)) {
831                 BIO_printf(bio_err, "Error Loading command line extensions\n");
832                 goto end;
833             }
834             i = do_X509_REQ_sign(req, pkey, digest, sigopts);
835             if (!i) {
836                 ERR_print_errors(bio_err);
837                 goto end;
838             }
839         }
840     }
841
842     if (subj && x509) {
843         BIO_printf(bio_err, "Cannot modify certificate subject\n");
844         goto end;
845     }
846
847     if (subj && !x509) {
848         if (verbose) {
849             BIO_printf(bio_err, "Modifying Request's Subject\n");
850             print_name(bio_err, "old subject=",
851                        X509_REQ_get_subject_name(req), get_nameopt());
852         }
853
854         if (build_subject(req, subj, chtype, multirdn) == 0) {
855             BIO_printf(bio_err, "ERROR: cannot modify subject\n");
856             ret = 1;
857             goto end;
858         }
859
860         if (verbose) {
861             print_name(bio_err, "new subject=",
862                        X509_REQ_get_subject_name(req), get_nameopt());
863         }
864     }
865
866     if (verify && !x509) {
867         EVP_PKEY *tpubkey = pkey;
868
869         if (tpubkey == NULL) {
870             tpubkey = X509_REQ_get0_pubkey(req);
871             if (tpubkey == NULL)
872                 goto end;
873         }
874
875         i = do_X509_REQ_verify(req, tpubkey, vfyopts);
876
877         if (i < 0) {
878             goto end;
879         } else if (i == 0) {
880             BIO_printf(bio_err, "verify failure\n");
881             ERR_print_errors(bio_err);
882         } else {                 /* if (i > 0) */
883             BIO_printf(bio_err, "verify OK\n");
884         }
885     }
886
887     if (noout && !text && !modulus && !subject && !pubkey) {
888         ret = 0;
889         goto end;
890     }
891
892     out = bio_open_default(outfile,
893                            keyout != NULL && outfile != NULL &&
894                            strcmp(keyout, outfile) == 0 ? 'a' : 'w',
895                            outformat);
896     if (out == NULL)
897         goto end;
898
899     if (pubkey) {
900         EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
901
902         if (tpubkey == NULL) {
903             BIO_printf(bio_err, "Error getting public key\n");
904             ERR_print_errors(bio_err);
905             goto end;
906         }
907         PEM_write_bio_PUBKEY(out, tpubkey);
908     }
909
910     if (text) {
911         if (x509)
912             ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
913         else
914             ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
915
916         if (ret == 0) {
917             if (x509)
918               BIO_printf(bio_err, "Error printing certificate\n");
919             else
920               BIO_printf(bio_err, "Error printing certificate request\n");
921
922             ERR_print_errors(bio_err);
923             goto end;
924         }
925     }
926
927     if (subject) {
928         if (x509)
929             print_name(out, "subject=", X509_get_subject_name(x509ss),
930                        get_nameopt());
931         else
932             print_name(out, "subject=", X509_REQ_get_subject_name(req),
933                        get_nameopt());
934     }
935
936     if (modulus) {
937         EVP_PKEY *tpubkey;
938
939         if (x509)
940             tpubkey = X509_get0_pubkey(x509ss);
941         else
942             tpubkey = X509_REQ_get0_pubkey(req);
943         if (tpubkey == NULL) {
944             fprintf(stdout, "Modulus=unavailable\n");
945             goto end;
946         }
947         fprintf(stdout, "Modulus=");
948 #ifndef OPENSSL_NO_RSA
949         if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
950             const BIGNUM *n;
951             RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
952             BN_print(out, n);
953         } else
954 #endif
955             fprintf(stdout, "Wrong Algorithm type");
956         fprintf(stdout, "\n");
957     }
958
959     if (!noout && !x509) {
960         if (outformat == FORMAT_ASN1)
961             i = i2d_X509_REQ_bio(out, req);
962         else if (newhdr)
963             i = PEM_write_bio_X509_REQ_NEW(out, req);
964         else
965             i = PEM_write_bio_X509_REQ(out, req);
966         if (!i) {
967             BIO_printf(bio_err, "unable to write X509 request\n");
968             goto end;
969         }
970     }
971     if (!noout && x509 && (x509ss != NULL)) {
972         if (outformat == FORMAT_ASN1)
973             i = i2d_X509_bio(out, x509ss);
974         else
975             i = PEM_write_bio_X509(out, x509ss);
976         if (!i) {
977             BIO_printf(bio_err, "unable to write X509 certificate\n");
978             goto end;
979         }
980     }
981     ret = 0;
982  end:
983     if (ret) {
984         ERR_print_errors(bio_err);
985     }
986     NCONF_free(req_conf);
987     NCONF_free(addext_conf);
988     BIO_free(addext_bio);
989     BIO_free_all(out);
990     EVP_PKEY_free(pkey);
991     EVP_PKEY_CTX_free(genctx);
992     sk_OPENSSL_STRING_free(pkeyopts);
993     sk_OPENSSL_STRING_free(sigopts);
994     sk_OPENSSL_STRING_free(vfyopts);
995     lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
996     lh_OPENSSL_STRING_free(addexts);
997 #ifndef OPENSSL_NO_ENGINE
998     ENGINE_free(gen_eng);
999 #endif
1000     OPENSSL_free(keyalgstr);
1001     X509_REQ_free(req);
1002     X509_free(x509ss);
1003     ASN1_INTEGER_free(serial);
1004     release_engine(e);
1005     if (passin != nofree_passin)
1006         OPENSSL_free(passin);
1007     if (passout != nofree_passout)
1008         OPENSSL_free(passout);
1009     return ret;
1010 }
1011
1012 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1013                     int attribs, unsigned long chtype)
1014 {
1015     int ret = 0, i;
1016     char no_prompt = 0;
1017     STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1018     char *tmp, *dn_sect, *attr_sect;
1019
1020     tmp = NCONF_get_string(req_conf, section, PROMPT);
1021     if (tmp == NULL)
1022         ERR_clear_error();
1023     if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1024         no_prompt = 1;
1025
1026     dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1027     if (dn_sect == NULL) {
1028         BIO_printf(bio_err, "unable to find '%s' in config\n",
1029                    DISTINGUISHED_NAME);
1030         goto err;
1031     }
1032     dn_sk = NCONF_get_section(req_conf, dn_sect);
1033     if (dn_sk == NULL) {
1034         BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1035         goto err;
1036     }
1037
1038     attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1039     if (attr_sect == NULL) {
1040         ERR_clear_error();
1041         attr_sk = NULL;
1042     } else {
1043         attr_sk = NCONF_get_section(req_conf, attr_sect);
1044         if (attr_sk == NULL) {
1045             BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1046             goto err;
1047         }
1048     }
1049
1050     /* setup version number */
1051     if (!X509_REQ_set_version(req, 0L))
1052         goto err;               /* version 1 */
1053
1054     if (subj)
1055         i = build_subject(req, subj, chtype, multirdn);
1056     else if (no_prompt)
1057         i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1058     else
1059         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1060                         chtype);
1061     if (!i)
1062         goto err;
1063
1064     if (!X509_REQ_set_pubkey(req, pkey))
1065         goto err;
1066
1067     ret = 1;
1068  err:
1069     return ret;
1070 }
1071
1072 /*
1073  * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1074  * where characters may be escaped by \
1075  */
1076 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1077                          int multirdn)
1078 {
1079     X509_NAME *n;
1080
1081     if ((n = parse_name(subject, chtype, multirdn, "subject")) == NULL)
1082         return 0;
1083
1084     if (!X509_REQ_set_subject_name(req, n)) {
1085         X509_NAME_free(n);
1086         return 0;
1087     }
1088     X509_NAME_free(n);
1089     return 1;
1090 }
1091
1092 static int prompt_info(X509_REQ *req,
1093                        STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1094                        STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1095                        int attribs, unsigned long chtype)
1096 {
1097     int i;
1098     char *p, *q;
1099     char buf[100];
1100     int nid, mval;
1101     long n_min, n_max;
1102     char *type, *value;
1103     const char *def;
1104     CONF_VALUE *v;
1105     X509_NAME *subj = X509_REQ_get_subject_name(req);
1106
1107     if (!batch) {
1108         BIO_printf(bio_err,
1109                    "You are about to be asked to enter information that will be incorporated\n");
1110         BIO_printf(bio_err, "into your certificate request.\n");
1111         BIO_printf(bio_err,
1112                    "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1113         BIO_printf(bio_err,
1114                    "There are quite a few fields but you can leave some blank\n");
1115         BIO_printf(bio_err,
1116                    "For some fields there will be a default value,\n");
1117         BIO_printf(bio_err,
1118                    "If you enter '.', the field will be left blank.\n");
1119         BIO_printf(bio_err, "-----\n");
1120     }
1121
1122     if (sk_CONF_VALUE_num(dn_sk)) {
1123         i = -1;
1124  start:
1125         for ( ; ; ) {
1126             i++;
1127             if (sk_CONF_VALUE_num(dn_sk) <= i)
1128                 break;
1129
1130             v = sk_CONF_VALUE_value(dn_sk, i);
1131             p = q = NULL;
1132             type = v->name;
1133             if (!check_end(type, "_min") || !check_end(type, "_max") ||
1134                 !check_end(type, "_default") || !check_end(type, "_value"))
1135                 continue;
1136             /*
1137              * Skip past any leading X. X: X, etc to allow for multiple
1138              * instances
1139              */
1140             for (p = v->name; *p; p++)
1141                 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1142                     p++;
1143                     if (*p)
1144                         type = p;
1145                     break;
1146                 }
1147             if (*type == '+') {
1148                 mval = -1;
1149                 type++;
1150             } else {
1151                 mval = 0;
1152             }
1153             /* If OBJ not recognised ignore it */
1154             if ((nid = OBJ_txt2nid(type)) == NID_undef)
1155                 goto start;
1156             if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1157                 return 0;
1158             if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1159                 ERR_clear_error();
1160                 def = "";
1161             }
1162
1163             if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1164                 return 0;
1165             if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1166                 ERR_clear_error();
1167                 value = NULL;
1168             }
1169
1170             if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1171                 return 0;
1172             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1173                 ERR_clear_error();
1174                 n_min = -1;
1175             }
1176
1177
1178             if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1179                 return 0;
1180             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1181                 ERR_clear_error();
1182                 n_max = -1;
1183             }
1184
1185             if (!add_DN_object(subj, v->value, def, value, nid,
1186                                n_min, n_max, chtype, mval))
1187                 return 0;
1188         }
1189         if (X509_NAME_entry_count(subj) == 0) {
1190             BIO_printf(bio_err, "error, no objects specified in config file\n");
1191             return 0;
1192         }
1193
1194         if (attribs) {
1195             if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1196                 && (!batch)) {
1197                 BIO_printf(bio_err,
1198                            "\nPlease enter the following 'extra' attributes\n");
1199                 BIO_printf(bio_err,
1200                            "to be sent with your certificate request\n");
1201             }
1202
1203             i = -1;
1204  start2:
1205             for ( ; ; ) {
1206                 i++;
1207                 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1208                     break;
1209
1210                 v = sk_CONF_VALUE_value(attr_sk, i);
1211                 type = v->name;
1212                 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1213                     goto start2;
1214
1215                 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1216                     return 0;
1217                 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1218                     == NULL) {
1219                     ERR_clear_error();
1220                     def = "";
1221                 }
1222
1223                 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1224                     return 0;
1225                 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1226                     == NULL) {
1227                     ERR_clear_error();
1228                     value = NULL;
1229                 }
1230
1231                 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1232                     return 0;
1233                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1234                     ERR_clear_error();
1235                     n_min = -1;
1236                 }
1237
1238                 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1239                     return 0;
1240                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1241                     ERR_clear_error();
1242                     n_max = -1;
1243                 }
1244
1245                 if (!add_attribute_object(req,
1246                                           v->value, def, value, nid, n_min,
1247                                           n_max, chtype))
1248                     return 0;
1249             }
1250         }
1251     } else {
1252         BIO_printf(bio_err, "No template, please set one up.\n");
1253         return 0;
1254     }
1255
1256     return 1;
1257
1258 }
1259
1260 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1261                      STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1262                      unsigned long chtype)
1263 {
1264     int i, spec_char, plus_char;
1265     char *p, *q;
1266     char *type;
1267     CONF_VALUE *v;
1268     X509_NAME *subj;
1269
1270     subj = X509_REQ_get_subject_name(req);
1271
1272     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1273         int mval;
1274         v = sk_CONF_VALUE_value(dn_sk, i);
1275         p = q = NULL;
1276         type = v->name;
1277         /*
1278          * Skip past any leading X. X: X, etc to allow for multiple instances
1279          */
1280         for (p = v->name; *p; p++) {
1281 #ifndef CHARSET_EBCDIC
1282             spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1283 #else
1284             spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1285                     || (*p == os_toascii['.']));
1286 #endif
1287             if (spec_char) {
1288                 p++;
1289                 if (*p)
1290                     type = p;
1291                 break;
1292             }
1293         }
1294 #ifndef CHARSET_EBCDIC
1295         plus_char = (*type == '+');
1296 #else
1297         plus_char = (*type == os_toascii['+']);
1298 #endif
1299         if (plus_char) {
1300             type++;
1301             mval = -1;
1302         } else {
1303             mval = 0;
1304         }
1305         if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1306                                         (unsigned char *)v->value, -1, -1,
1307                                         mval))
1308             return 0;
1309
1310     }
1311
1312     if (!X509_NAME_entry_count(subj)) {
1313         BIO_printf(bio_err, "error, no objects specified in config file\n");
1314         return 0;
1315     }
1316     if (attribs) {
1317         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1318             v = sk_CONF_VALUE_value(attr_sk, i);
1319             if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1320                                            (unsigned char *)v->value, -1))
1321                 return 0;
1322         }
1323     }
1324     return 1;
1325 }
1326
1327 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1328                          char *value, int nid, int n_min, int n_max,
1329                          unsigned long chtype, int mval)
1330 {
1331     int ret = 0;
1332     char buf[1024];
1333
1334     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1335                      "DN value", "DN default");
1336     if ((ret == 0) || (ret == 1))
1337         return ret;
1338     ret = 1;
1339
1340     if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1341                                     (unsigned char *)buf, -1, -1, mval))
1342         ret = 0;
1343
1344     return ret;
1345 }
1346
1347 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1348                                 char *value, int nid, int n_min,
1349                                 int n_max, unsigned long chtype)
1350 {
1351     int ret = 0;
1352     char buf[1024];
1353
1354     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1355                      "Attribute value", "Attribute default");
1356     if ((ret == 0) || (ret == 1))
1357         return ret;
1358     ret = 1;
1359
1360     if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1361                                    (unsigned char *)buf, -1)) {
1362         BIO_printf(bio_err, "Error adding attribute\n");
1363         ERR_print_errors(bio_err);
1364         ret = 0;
1365     }
1366
1367     return ret;
1368 }
1369
1370
1371 static int build_data(char *text, const char *def,
1372                          char *value, int n_min, int n_max,
1373                          char *buf, const int buf_size,
1374                          const char *desc1, const char *desc2
1375                          )
1376 {
1377     int i;
1378  start:
1379     if (!batch)
1380         BIO_printf(bio_err, "%s [%s]:", text, def);
1381     (void)BIO_flush(bio_err);
1382     if (value != NULL) {
1383         if (!join(buf, buf_size, value, "\n", desc1))
1384             return 0;
1385         BIO_printf(bio_err, "%s\n", value);
1386     } else {
1387         buf[0] = '\0';
1388         if (!batch) {
1389             if (!fgets(buf, buf_size, stdin))
1390                 return 0;
1391         } else {
1392             buf[0] = '\n';
1393             buf[1] = '\0';
1394         }
1395     }
1396
1397     if (buf[0] == '\0')
1398         return 0;
1399     if (buf[0] == '\n') {
1400         if ((def == NULL) || (def[0] == '\0'))
1401             return 1;
1402         if (!join(buf, buf_size, def, "\n", desc2))
1403             return 0;
1404     } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1405         return 1;
1406     }
1407
1408     i = strlen(buf);
1409     if (buf[i - 1] != '\n') {
1410         BIO_printf(bio_err, "weird input :-(\n");
1411         return 0;
1412     }
1413     buf[--i] = '\0';
1414 #ifdef CHARSET_EBCDIC
1415     ebcdic2ascii(buf, buf, i);
1416 #endif
1417     if (!req_check_len(i, n_min, n_max)) {
1418         if (batch || value)
1419             return 0;
1420         goto start;
1421     }
1422     return 2;
1423 }
1424
1425 static int req_check_len(int len, int n_min, int n_max)
1426 {
1427     if ((n_min > 0) && (len < n_min)) {
1428         BIO_printf(bio_err,
1429                    "string is too short, it needs to be at least %d bytes long\n",
1430                    n_min);
1431         return 0;
1432     }
1433     if ((n_max >= 0) && (len > n_max)) {
1434         BIO_printf(bio_err,
1435                    "string is too long, it needs to be no more than %d bytes long\n",
1436                    n_max);
1437         return 0;
1438     }
1439     return 1;
1440 }
1441
1442 /* Check if the end of a string matches 'end' */
1443 static int check_end(const char *str, const char *end)
1444 {
1445     size_t elen, slen;
1446     const char *tmp;
1447
1448     elen = strlen(end);
1449     slen = strlen(str);
1450     if (elen > slen)
1451         return 1;
1452     tmp = str + slen - elen;
1453     return strcmp(tmp, end);
1454 }
1455
1456 /*
1457  * Merge the two strings together into the result buffer checking for
1458  * overflow and producing an error message if there is.
1459  */
1460 static int join(char buf[], size_t buf_size, const char *name,
1461                 const char *tail, const char *desc)
1462 {
1463     const size_t name_len = strlen(name), tail_len = strlen(tail);
1464
1465     if (name_len + tail_len + 1 > buf_size) {
1466         BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1467         return 0;
1468     }
1469     memcpy(buf, name, name_len);
1470     memcpy(buf + name_len, tail, tail_len + 1);
1471     return 1;
1472 }
1473
1474 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1475                                     int *pkey_type, long *pkeylen,
1476                                     char **palgnam, ENGINE *keygen_engine)
1477 {
1478     EVP_PKEY_CTX *gctx = NULL;
1479     EVP_PKEY *param = NULL;
1480     long keylen = -1;
1481     BIO *pbio = NULL;
1482     const char *paramfile = NULL;
1483
1484     if (gstr == NULL) {
1485         *pkey_type = EVP_PKEY_RSA;
1486         keylen = *pkeylen;
1487     } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1488         *pkey_type = EVP_PKEY_RSA;
1489         keylen = atol(gstr);
1490         *pkeylen = keylen;
1491     } else if (strncmp(gstr, "param:", 6) == 0) {
1492         paramfile = gstr + 6;
1493     } else {
1494         const char *p = strchr(gstr, ':');
1495         int len;
1496         ENGINE *tmpeng;
1497         const EVP_PKEY_ASN1_METHOD *ameth;
1498
1499         if (p != NULL)
1500             len = p - gstr;
1501         else
1502             len = strlen(gstr);
1503         /*
1504          * The lookup of a the string will cover all engines so keep a note
1505          * of the implementation.
1506          */
1507
1508         ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1509
1510         if (ameth == NULL) {
1511             BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1512             return NULL;
1513         }
1514
1515         EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1516 #ifndef OPENSSL_NO_ENGINE
1517         ENGINE_finish(tmpeng);
1518 #endif
1519         if (*pkey_type == EVP_PKEY_RSA) {
1520             if (p != NULL) {
1521                 keylen = atol(p + 1);
1522                 *pkeylen = keylen;
1523             } else {
1524                 keylen = *pkeylen;
1525             }
1526         } else if (p != NULL) {
1527             paramfile = p + 1;
1528         }
1529     }
1530
1531     if (paramfile != NULL) {
1532         pbio = BIO_new_file(paramfile, "r");
1533         if (pbio == NULL) {
1534             BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1535             return NULL;
1536         }
1537         param = PEM_read_bio_Parameters(pbio, NULL);
1538
1539         if (param == NULL) {
1540             X509 *x;
1541
1542             (void)BIO_reset(pbio);
1543             x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1544             if (x != NULL) {
1545                 param = X509_get_pubkey(x);
1546                 X509_free(x);
1547             }
1548         }
1549
1550         BIO_free(pbio);
1551
1552         if (param == NULL) {
1553             BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1554             return NULL;
1555         }
1556         if (*pkey_type == -1) {
1557             *pkey_type = EVP_PKEY_id(param);
1558         } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1559             BIO_printf(bio_err, "Key Type does not match parameters\n");
1560             EVP_PKEY_free(param);
1561             return NULL;
1562         }
1563     }
1564
1565     if (palgnam != NULL) {
1566         const EVP_PKEY_ASN1_METHOD *ameth;
1567         ENGINE *tmpeng;
1568         const char *anam;
1569
1570         ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1571         if (ameth == NULL) {
1572             BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1573             return NULL;
1574         }
1575         EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1576         *palgnam = OPENSSL_strdup(anam);
1577 #ifndef OPENSSL_NO_ENGINE
1578         ENGINE_finish(tmpeng);
1579 #endif
1580     }
1581
1582     if (param != NULL) {
1583         gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1584         *pkeylen = EVP_PKEY_bits(param);
1585         EVP_PKEY_free(param);
1586     } else {
1587         gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1588     }
1589
1590     if (gctx == NULL) {
1591         BIO_puts(bio_err, "Error allocating keygen context\n");
1592         ERR_print_errors(bio_err);
1593         return NULL;
1594     }
1595
1596     if (EVP_PKEY_keygen_init(gctx) <= 0) {
1597         BIO_puts(bio_err, "Error initializing keygen context\n");
1598         ERR_print_errors(bio_err);
1599         EVP_PKEY_CTX_free(gctx);
1600         return NULL;
1601     }
1602 #ifndef OPENSSL_NO_RSA
1603     if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1604         if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1605             BIO_puts(bio_err, "Error setting RSA keysize\n");
1606             ERR_print_errors(bio_err);
1607             EVP_PKEY_CTX_free(gctx);
1608             return NULL;
1609         }
1610     }
1611 #endif
1612
1613     return gctx;
1614 }
1615
1616 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1617 {
1618     char c = '*';
1619     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1620     int p;
1621     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1622     if (p == 0)
1623         c = '.';
1624     if (p == 1)
1625         c = '+';
1626     if (p == 2)
1627         c = '*';
1628     if (p == 3)
1629         c = '\n';
1630     BIO_write(b, &c, 1);
1631     (void)BIO_flush(b);
1632     return 1;
1633 }
1634
1635 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
1636 {
1637     int i;
1638
1639     if (opts == NULL)
1640         return 1;
1641
1642     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1643         char *opt = sk_OPENSSL_STRING_value(opts, i);
1644         if (pkey_ctrl_string(pkctx, opt) <= 0) {
1645             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1646             ERR_print_errors(bio_err);
1647             return 0;
1648         }
1649     }
1650
1651     return 1;
1652 }
1653
1654 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
1655 {
1656     int i;
1657
1658     if (opts == NULL)
1659         return 1;
1660
1661     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1662         char *opt = sk_OPENSSL_STRING_value(opts, i);
1663         if (x509_ctrl_string(x, opt) <= 0) {
1664             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1665             ERR_print_errors(bio_err);
1666             return 0;
1667         }
1668     }
1669
1670     return 1;
1671 }
1672
1673 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
1674 {
1675     int i;
1676
1677     if (opts == NULL)
1678         return 1;
1679
1680     for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1681         char *opt = sk_OPENSSL_STRING_value(opts, i);
1682         if (x509_req_ctrl_string(x, opt) <= 0) {
1683             BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1684             ERR_print_errors(bio_err);
1685             return 0;
1686         }
1687     }
1688
1689     return 1;
1690 }
1691
1692 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1693                         const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1694 {
1695     EVP_PKEY_CTX *pkctx = NULL;
1696     int def_nid;
1697
1698     if (ctx == NULL)
1699         return 0;
1700     /*
1701      * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1702      * for this algorithm.
1703      */
1704     if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1705             && def_nid == NID_undef) {
1706         /* The signing algorithm requires there to be no digest */
1707         md = NULL;
1708     }
1709     return EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey)
1710         && do_pkey_ctx_init(pkctx, sigopts);
1711 }
1712
1713 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1714                  STACK_OF(OPENSSL_STRING) *sigopts)
1715 {
1716     int rv = 0;
1717     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1718
1719     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1720         rv = (X509_sign_ctx(x, mctx) > 0);
1721     EVP_MD_CTX_free(mctx);
1722     return rv;
1723 }
1724
1725 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1726                      STACK_OF(OPENSSL_STRING) *sigopts)
1727 {
1728     int rv = 0;
1729     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1730
1731     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1732         rv = (X509_REQ_sign_ctx(x, mctx) > 0);
1733     EVP_MD_CTX_free(mctx);
1734     return rv;
1735 }
1736
1737 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
1738 {
1739     int rv = 0;
1740
1741     if (do_x509_init(x, vfyopts) > 0)
1742         rv = (X509_verify(x, pkey) > 0);
1743     return rv;
1744 }
1745
1746 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
1747                        STACK_OF(OPENSSL_STRING) *vfyopts)
1748 {
1749     int rv = 0;
1750
1751     if (do_x509_req_init(x, vfyopts) > 0)
1752         rv = (X509_REQ_verify(x, pkey) > 0);
1753     return rv;
1754 }
1755
1756 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1757                      STACK_OF(OPENSSL_STRING) *sigopts)
1758 {
1759     int rv = 0;
1760     EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1761
1762     if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1763         rv = (X509_CRL_sign_ctx(x, mctx) > 0);
1764     EVP_MD_CTX_free(mctx);
1765     return rv;
1766 }