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