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