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