xref: /freebsd/crypto/openssl/apps/req.c (revision 069ac18495ad8fde2748bc94b0f80a50250bb01d)
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         if (pkey == NULL)
689             goto end;
690 
691         EVP_PKEY_CTX_free(genctx);
692         genctx = NULL;
693     }
694     if (keyout == NULL && keyfile == NULL) {
695         keyout = NCONF_get_string(req_conf, section, KEYFILE);
696         if (keyout == NULL)
697             ERR_clear_error();
698     }
699 
700     if (pkey != NULL && (keyfile == NULL || keyout != NULL)) {
701         if (verbose) {
702             BIO_printf(bio_err, "Writing private key to ");
703             if (keyout == NULL)
704                 BIO_printf(bio_err, "stdout\n");
705             else
706                 BIO_printf(bio_err, "'%s'\n", keyout);
707         }
708         out = bio_open_owner(keyout, outformat, newreq);
709         if (out == NULL)
710             goto end;
711 
712         p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
713         if (p == NULL) {
714             ERR_clear_error();
715             p = NCONF_get_string(req_conf, section, "encrypt_key");
716             if (p == NULL)
717                 ERR_clear_error();
718         }
719         if ((p != NULL) && (strcmp(p, "no") == 0))
720             cipher = NULL;
721         if (noenc)
722             cipher = NULL;
723 
724         i = 0;
725  loop:
726         if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
727                                       NULL, 0, NULL, passout)) {
728             if ((ERR_GET_REASON(ERR_peek_error()) ==
729                  PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
730                 ERR_clear_error();
731                 i++;
732                 goto loop;
733             }
734             goto end;
735         }
736         BIO_free(out);
737         out = NULL;
738         BIO_printf(bio_err, "-----\n");
739     }
740 
741     /*
742      * subj is expected to be in the format /type0=value0/type1=value1/type2=...
743      * where characters may be escaped by \
744      */
745     if (subj != NULL
746             && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
747         goto end;
748 
749     if (!newreq) {
750         req = load_csr(infile /* if NULL, reads from stdin */,
751                        informat, "X509 request");
752         if (req == NULL)
753             goto end;
754     }
755 
756     if (CAkeyfile == NULL)
757         CAkeyfile = CAfile;
758     if (CAkeyfile != NULL) {
759         if (CAfile == NULL) {
760             BIO_printf(bio_err,
761                        "Warning: Ignoring -CAkey option since no -CA option is given\n");
762         } else {
763             if ((CAkey = load_key(CAkeyfile, FORMAT_UNDEF,
764                                   0, passin, e,
765                                   CAkeyfile != CAfile
766                                   ? "issuer private key from -CAkey arg"
767                                   : "issuer private key from -CA arg")) == NULL)
768                 goto end;
769         }
770     }
771     if (CAfile != NULL) {
772         if ((CAcert = load_cert_pass(CAfile, FORMAT_UNDEF, 1, passin,
773                                      "issuer cert from -CA arg")) == NULL)
774             goto end;
775         if (!X509_check_private_key(CAcert, CAkey)) {
776             BIO_printf(bio_err,
777                        "Issuer CA certificate and key do not match\n");
778             goto end;
779         }
780     }
781     if (newreq || gen_x509) {
782         if (CAcert == NULL && pkey == NULL) {
783             BIO_printf(bio_err, "Must provide a signature key using -key or"
784                 " provide -CA / -CAkey\n");
785             goto end;
786         }
787 
788         if (req == NULL) {
789             req = X509_REQ_new_ex(app_get0_libctx(), app_get0_propq());
790             if (req == NULL) {
791                 goto end;
792             }
793 
794             if (!make_REQ(req, pkey, fsubj, multirdn, !gen_x509, chtype)){
795                 BIO_printf(bio_err, "Error making certificate request\n");
796                 goto end;
797             }
798             /* Note that -x509 can take over -key and -subj option values. */
799         }
800         if (gen_x509) {
801             EVP_PKEY *pub_key = X509_REQ_get0_pubkey(req);
802             EVP_PKEY *issuer_key = CAcert != NULL ? CAkey : pkey;
803             X509V3_CTX ext_ctx;
804             X509_NAME *issuer = CAcert != NULL ? X509_get_subject_name(CAcert) :
805                 X509_REQ_get_subject_name(req);
806             X509_NAME *n_subj = fsubj != NULL ? fsubj :
807                 X509_REQ_get_subject_name(req);
808 
809             if ((new_x509 = X509_new_ex(app_get0_libctx(),
810                                         app_get0_propq())) == NULL)
811                 goto end;
812 
813             if (serial != NULL) {
814                 if (!X509_set_serialNumber(new_x509, serial))
815                     goto end;
816             } else {
817                 if (!rand_serial(NULL, X509_get_serialNumber(new_x509)))
818                     goto end;
819             }
820 
821             if (!X509_set_issuer_name(new_x509, issuer))
822                 goto end;
823             if (days == UNSET_DAYS) {
824                 days = DEFAULT_DAYS;
825             }
826             if (!set_cert_times(new_x509, NULL, NULL, days))
827                 goto end;
828             if (!X509_set_subject_name(new_x509, n_subj))
829                 goto end;
830             if (!pub_key || !X509_set_pubkey(new_x509, pub_key))
831                 goto end;
832             if (ext_copy == EXT_COPY_UNSET) {
833                 if (infile != NULL)
834                     BIO_printf(bio_err, "Warning: No -copy_extensions given; ignoring any extensions in the request\n");
835             } else if (!copy_extensions(new_x509, req, ext_copy)) {
836                 BIO_printf(bio_err, "Error copying extensions from request\n");
837                 goto end;
838             }
839 
840             /* Set up V3 context struct */
841             X509V3_set_ctx(&ext_ctx, CAcert != NULL ? CAcert : new_x509,
842                            new_x509, NULL, NULL, X509V3_CTX_REPLACE);
843             /* prepare fallback for AKID, but only if issuer cert == new_x509 */
844             if (CAcert == NULL) {
845                 if (!X509V3_set_issuer_pkey(&ext_ctx, issuer_key))
846                     goto end;
847                 ERR_set_mark();
848                 if (!X509_check_private_key(new_x509, issuer_key))
849                     BIO_printf(bio_err,
850                                "Warning: Signature key and public key of cert do not match\n");
851                 ERR_pop_to_mark();
852             }
853             X509V3_set_nconf(&ext_ctx, req_conf);
854 
855             /* Add extensions */
856             if (extensions != NULL
857                     && !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extensions,
858                                              new_x509)) {
859                 BIO_printf(bio_err, "Error adding x509 extensions from section %s\n",
860                            extensions);
861                 goto end;
862             }
863             if (addext_conf != NULL
864                 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
865                                          new_x509)) {
866                 BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
867                 goto end;
868             }
869 
870             /* If a pre-cert was requested, we need to add a poison extension */
871             if (precert) {
872                 if (X509_add1_ext_i2d(new_x509, NID_ct_precert_poison,
873                                       NULL, 1, 0) != 1) {
874                     BIO_printf(bio_err, "Error adding poison extension\n");
875                     goto end;
876                 }
877             }
878 
879             i = do_X509_sign(new_x509, issuer_key, digest, sigopts, &ext_ctx);
880             if (!i)
881                 goto end;
882         } else {
883             X509V3_CTX ext_ctx;
884 
885             /* Set up V3 context struct */
886             X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
887             X509V3_set_nconf(&ext_ctx, req_conf);
888 
889             /* Add extensions */
890             if (req_exts != NULL
891                 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
892                                              req_exts, req)) {
893                 BIO_printf(bio_err, "Error adding request extensions from section %s\n",
894                            req_exts);
895                 goto end;
896             }
897             if (addext_conf != NULL
898                 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
899                                              req)) {
900                 BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
901                 goto end;
902             }
903             i = do_X509_REQ_sign(req, pkey, digest, sigopts);
904             if (!i)
905                 goto end;
906         }
907     }
908 
909     if (subj != NULL && !newreq && !gen_x509) {
910         if (verbose) {
911             BIO_printf(out, "Modifying subject of certificate request\n");
912             print_name(out, "Old subject=", X509_REQ_get_subject_name(req));
913         }
914 
915         if (!X509_REQ_set_subject_name(req, fsubj)) {
916             BIO_printf(bio_err, "Error modifying subject of certificate request\n");
917             goto end;
918         }
919 
920         if (verbose) {
921             print_name(out, "New subject=", X509_REQ_get_subject_name(req));
922         }
923     }
924 
925     if (verify) {
926         EVP_PKEY *tpubkey = pkey;
927 
928         if (tpubkey == NULL) {
929             tpubkey = X509_REQ_get0_pubkey(req);
930             if (tpubkey == NULL)
931                 goto end;
932         }
933 
934         i = do_X509_REQ_verify(req, tpubkey, vfyopts);
935 
936         if (i < 0)
937             goto end;
938         if (i == 0)
939             BIO_printf(bio_err, "Certificate request self-signature verify failure\n");
940         else /* i > 0 */
941             BIO_printf(bio_err, "Certificate request self-signature verify OK\n");
942     }
943 
944     if (noout && !text && !modulus && !subject && !pubkey) {
945         ret = 0;
946         goto end;
947     }
948 
949     out = bio_open_default(outfile,
950                            keyout != NULL && outfile != NULL &&
951                            strcmp(keyout, outfile) == 0 ? 'a' : 'w',
952                            outformat);
953     if (out == NULL)
954         goto end;
955 
956     if (pubkey) {
957         EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
958 
959         if (tpubkey == NULL) {
960             BIO_printf(bio_err, "Error getting public key\n");
961             goto end;
962         }
963         PEM_write_bio_PUBKEY(out, tpubkey);
964     }
965 
966     if (text) {
967         if (gen_x509)
968             ret = X509_print_ex(out, new_x509, get_nameopt(), reqflag);
969         else
970             ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
971 
972         if (ret == 0) {
973             if (gen_x509)
974                 BIO_printf(bio_err, "Error printing certificate\n");
975             else
976                 BIO_printf(bio_err, "Error printing certificate request\n");
977             goto end;
978         }
979     }
980 
981     if (subject) {
982         print_name(out, "subject=", gen_x509
983                    ? X509_get_subject_name(new_x509)
984                    : X509_REQ_get_subject_name(req));
985     }
986 
987     if (modulus) {
988         EVP_PKEY *tpubkey;
989 
990         if (gen_x509)
991             tpubkey = X509_get0_pubkey(new_x509);
992         else
993             tpubkey = X509_REQ_get0_pubkey(req);
994         if (tpubkey == NULL) {
995             BIO_puts(bio_err, "Modulus is unavailable\n");
996             goto end;
997         }
998         BIO_puts(out, "Modulus=");
999         if (EVP_PKEY_is_a(tpubkey, "RSA") || EVP_PKEY_is_a(tpubkey, "RSA-PSS")) {
1000             BIGNUM *n = NULL;
1001 
1002             if (!EVP_PKEY_get_bn_param(tpubkey, "n", &n))
1003                 goto end;
1004             BN_print(out, n);
1005             BN_free(n);
1006         } else {
1007             BIO_puts(out, "Wrong Algorithm type");
1008         }
1009         BIO_puts(out, "\n");
1010     }
1011 
1012     if (!noout && !gen_x509) {
1013         if (outformat == FORMAT_ASN1)
1014             i = i2d_X509_REQ_bio(out, req);
1015         else if (newhdr)
1016             i = PEM_write_bio_X509_REQ_NEW(out, req);
1017         else
1018             i = PEM_write_bio_X509_REQ(out, req);
1019         if (!i) {
1020             BIO_printf(bio_err, "Unable to write certificate request\n");
1021             goto end;
1022         }
1023     }
1024     if (!noout && gen_x509 && new_x509 != NULL) {
1025         if (outformat == FORMAT_ASN1)
1026             i = i2d_X509_bio(out, new_x509);
1027         else
1028             i = PEM_write_bio_X509(out, new_x509);
1029         if (!i) {
1030             BIO_printf(bio_err, "Unable to write X509 certificate\n");
1031             goto end;
1032         }
1033     }
1034     ret = 0;
1035  end:
1036     if (ret) {
1037         ERR_print_errors(bio_err);
1038     }
1039     NCONF_free(req_conf);
1040     NCONF_free(addext_conf);
1041     BIO_free(addext_bio);
1042     BIO_free_all(out);
1043     EVP_PKEY_free(pkey);
1044     EVP_PKEY_CTX_free(genctx);
1045     sk_OPENSSL_STRING_free(pkeyopts);
1046     sk_OPENSSL_STRING_free(sigopts);
1047     sk_OPENSSL_STRING_free(vfyopts);
1048     lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
1049     lh_OPENSSL_STRING_free(addexts);
1050 #ifndef OPENSSL_NO_ENGINE
1051     release_engine(gen_eng);
1052 #endif
1053     OPENSSL_free(keyalgstr);
1054     X509_REQ_free(req);
1055     X509_NAME_free(fsubj);
1056     X509_free(new_x509);
1057     X509_free(CAcert);
1058     EVP_PKEY_free(CAkey);
1059     ASN1_INTEGER_free(serial);
1060     release_engine(e);
1061     if (passin != nofree_passin)
1062         OPENSSL_free(passin);
1063     if (passout != nofree_passout)
1064         OPENSSL_free(passout);
1065     return ret;
1066 }
1067 
1068 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
1069                     int multirdn, int attribs, unsigned long chtype)
1070 {
1071     int ret = 0, i;
1072     char no_prompt = 0;
1073     STACK_OF(CONF_VALUE) *dn_sk = NULL, *attr_sk = NULL;
1074     char *tmp, *dn_sect, *attr_sect;
1075 
1076     tmp = NCONF_get_string(req_conf, section, PROMPT);
1077     if (tmp == NULL)
1078         ERR_clear_error();
1079     if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1080         no_prompt = 1;
1081 
1082     dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1083     if (dn_sect == NULL) {
1084         ERR_clear_error();
1085     } else {
1086         dn_sk = NCONF_get_section(req_conf, dn_sect);
1087         if (dn_sk == NULL) {
1088             BIO_printf(bio_err, "Unable to get '%s' section\n", dn_sect);
1089             goto err;
1090         }
1091     }
1092 
1093     attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1094     if (attr_sect == NULL) {
1095         ERR_clear_error();
1096     } else {
1097         attr_sk = NCONF_get_section(req_conf, attr_sect);
1098         if (attr_sk == NULL) {
1099             BIO_printf(bio_err, "Unable to get '%s' section\n", attr_sect);
1100             goto err;
1101         }
1102     }
1103 
1104     /* so far there is only version 1 */
1105     if (!X509_REQ_set_version(req, X509_REQ_VERSION_1))
1106         goto err;
1107 
1108     if (fsubj != NULL)
1109         i = X509_REQ_set_subject_name(req, fsubj);
1110     else if (no_prompt)
1111         i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1112     else
1113         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1114                         chtype);
1115     if (!i)
1116         goto err;
1117 
1118     if (!X509_REQ_set_pubkey(req, pkey))
1119         goto err;
1120 
1121     ret = 1;
1122  err:
1123     return ret;
1124 }
1125 
1126 static int prompt_info(X509_REQ *req,
1127                        STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1128                        STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1129                        int attribs, unsigned long chtype)
1130 {
1131     int i;
1132     char *p, *q;
1133     char buf[100];
1134     int nid, mval;
1135     long n_min, n_max;
1136     char *type, *value;
1137     const char *def;
1138     CONF_VALUE *v;
1139     X509_NAME *subj = X509_REQ_get_subject_name(req);
1140 
1141     if (!batch) {
1142         BIO_printf(bio_err,
1143                    "You are about to be asked to enter information that will be incorporated\n");
1144         BIO_printf(bio_err, "into your certificate request.\n");
1145         BIO_printf(bio_err,
1146                    "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1147         BIO_printf(bio_err,
1148                    "There are quite a few fields but you can leave some blank\n");
1149         BIO_printf(bio_err,
1150                    "For some fields there will be a default value,\n");
1151         BIO_printf(bio_err,
1152                    "If you enter '.', the field will be left blank.\n");
1153         BIO_printf(bio_err, "-----\n");
1154     }
1155 
1156     if (sk_CONF_VALUE_num(dn_sk)) {
1157         i = -1;
1158  start:
1159         for (;;) {
1160             i++;
1161             if (sk_CONF_VALUE_num(dn_sk) <= i)
1162                 break;
1163 
1164             v = sk_CONF_VALUE_value(dn_sk, i);
1165             p = q = NULL;
1166             type = v->name;
1167             if (!check_end(type, "_min") || !check_end(type, "_max") ||
1168                 !check_end(type, "_default") || !check_end(type, "_value"))
1169                 continue;
1170             /*
1171              * Skip past any leading X. X: X, etc to allow for multiple
1172              * instances
1173              */
1174             for (p = v->name; *p; p++)
1175                 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1176                     p++;
1177                     if (*p)
1178                         type = p;
1179                     break;
1180                 }
1181             if (*type == '+') {
1182                 mval = -1;
1183                 type++;
1184             } else {
1185                 mval = 0;
1186             }
1187             /* If OBJ not recognised ignore it */
1188             if ((nid = OBJ_txt2nid(type)) == NID_undef)
1189                 goto start;
1190             if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1191                 return 0;
1192             if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1193                 ERR_clear_error();
1194                 def = "";
1195             }
1196 
1197             if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1198                 return 0;
1199             if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1200                 ERR_clear_error();
1201                 value = NULL;
1202             }
1203 
1204             if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1205                 return 0;
1206             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1207                 ERR_clear_error();
1208                 n_min = -1;
1209             }
1210 
1211             if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1212                 return 0;
1213             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1214                 ERR_clear_error();
1215                 n_max = -1;
1216             }
1217 
1218             if (!add_DN_object(subj, v->value, def, value, nid,
1219                                n_min, n_max, chtype, mval))
1220                 return 0;
1221         }
1222         if (X509_NAME_entry_count(subj) == 0) {
1223             BIO_printf(bio_err, "Error: No objects specified in config file\n");
1224             return 0;
1225         }
1226 
1227         if (attribs) {
1228             if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1229                 && (!batch)) {
1230                 BIO_printf(bio_err,
1231                            "\nPlease enter the following 'extra' attributes\n");
1232                 BIO_printf(bio_err,
1233                            "to be sent with your certificate request\n");
1234             }
1235 
1236             i = -1;
1237  start2:
1238             for (;;) {
1239                 i++;
1240                 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1241                     break;
1242 
1243                 v = sk_CONF_VALUE_value(attr_sk, i);
1244                 type = v->name;
1245                 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1246                     goto start2;
1247 
1248                 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1249                     return 0;
1250                 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1251                     == NULL) {
1252                     ERR_clear_error();
1253                     def = "";
1254                 }
1255 
1256                 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1257                     return 0;
1258                 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1259                     == NULL) {
1260                     ERR_clear_error();
1261                     value = NULL;
1262                 }
1263 
1264                 if (!join(buf, sizeof(buf), type, "_min", "Name"))
1265                     return 0;
1266                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1267                     ERR_clear_error();
1268                     n_min = -1;
1269                 }
1270 
1271                 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1272                     return 0;
1273                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1274                     ERR_clear_error();
1275                     n_max = -1;
1276                 }
1277 
1278                 if (!add_attribute_object(req,
1279                                           v->value, def, value, nid, n_min,
1280                                           n_max, chtype))
1281                     return 0;
1282             }
1283         }
1284     } else {
1285         BIO_printf(bio_err, "No template, please set one up.\n");
1286         return 0;
1287     }
1288 
1289     return 1;
1290 
1291 }
1292 
1293 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1294                      STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1295                      unsigned long chtype)
1296 {
1297     int i, spec_char, plus_char;
1298     char *p, *q;
1299     char *type;
1300     CONF_VALUE *v;
1301     X509_NAME *subj;
1302 
1303     subj = X509_REQ_get_subject_name(req);
1304 
1305     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1306         int mval;
1307         v = sk_CONF_VALUE_value(dn_sk, i);
1308         p = q = NULL;
1309         type = v->name;
1310         /*
1311          * Skip past any leading X. X: X, etc to allow for multiple instances
1312          */
1313         for (p = v->name; *p; p++) {
1314 #ifndef CHARSET_EBCDIC
1315             spec_char = (*p == ':' || *p == ',' || *p == '.');
1316 #else
1317             spec_char = (*p == os_toascii[':'] || *p == os_toascii[',']
1318                          || *p == os_toascii['.']);
1319 #endif
1320             if (spec_char) {
1321                 p++;
1322                 if (*p)
1323                     type = p;
1324                 break;
1325             }
1326         }
1327 #ifndef CHARSET_EBCDIC
1328         plus_char = (*type == '+');
1329 #else
1330         plus_char = (*type == os_toascii['+']);
1331 #endif
1332         if (plus_char) {
1333             type++;
1334             mval = -1;
1335         } else {
1336             mval = 0;
1337         }
1338         if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1339                                         (unsigned char *)v->value, -1, -1,
1340                                         mval))
1341             return 0;
1342 
1343     }
1344 
1345     if (!X509_NAME_entry_count(subj)) {
1346         BIO_printf(bio_err, "Error: No objects specified in config file\n");
1347         return 0;
1348     }
1349     if (attribs) {
1350         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1351             v = sk_CONF_VALUE_value(attr_sk, i);
1352             if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1353                                            (unsigned char *)v->value, -1))
1354                 return 0;
1355         }
1356     }
1357     return 1;
1358 }
1359 
1360 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1361                          char *value, int nid, int n_min, int n_max,
1362                          unsigned long chtype, int mval)
1363 {
1364     int ret = 0;
1365     char buf[1024];
1366 
1367     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1368                      "DN value", "DN default");
1369     if ((ret == 0) || (ret == 1))
1370         return ret;
1371     ret = 1;
1372 
1373     if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1374                                     (unsigned char *)buf, -1, -1, mval))
1375         ret = 0;
1376 
1377     return ret;
1378 }
1379 
1380 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1381                                 char *value, int nid, int n_min,
1382                                 int n_max, unsigned long chtype)
1383 {
1384     int ret = 0;
1385     char buf[1024];
1386 
1387     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1388                      "Attribute value", "Attribute default");
1389     if ((ret == 0) || (ret == 1))
1390         return ret;
1391     ret = 1;
1392 
1393     if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1394                                    (unsigned char *)buf, -1)) {
1395         BIO_printf(bio_err, "Error adding attribute\n");
1396         ret = 0;
1397     }
1398 
1399     return ret;
1400 }
1401 
1402 static int build_data(char *text, const char *def, char *value,
1403                       int n_min, int n_max, char *buf, const int buf_size,
1404                       const char *desc1, const char *desc2)
1405 {
1406     int i;
1407  start:
1408     if (!batch)
1409         BIO_printf(bio_err, "%s [%s]:", text, def);
1410     (void)BIO_flush(bio_err);
1411     if (value != NULL) {
1412         if (!join(buf, buf_size, value, "\n", desc1))
1413             return 0;
1414         BIO_printf(bio_err, "%s\n", value);
1415     } else {
1416         buf[0] = '\0';
1417         if (!batch) {
1418             if (!fgets(buf, buf_size, stdin))
1419                 return 0;
1420         } else {
1421             buf[0] = '\n';
1422             buf[1] = '\0';
1423         }
1424     }
1425 
1426     if (buf[0] == '\0')
1427         return 0;
1428     if (buf[0] == '\n') {
1429         if ((def == NULL) || (def[0] == '\0'))
1430             return 1;
1431         if (!join(buf, buf_size, def, "\n", desc2))
1432             return 0;
1433     } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1434         return 1;
1435     }
1436 
1437     i = strlen(buf);
1438     if (buf[i - 1] != '\n') {
1439         BIO_printf(bio_err, "Missing newline at end of input\n");
1440         return 0;
1441     }
1442     buf[--i] = '\0';
1443 #ifdef CHARSET_EBCDIC
1444     ebcdic2ascii(buf, buf, i);
1445 #endif
1446     if (!req_check_len(i, n_min, n_max)) {
1447         if (batch || value)
1448             return 0;
1449         goto start;
1450     }
1451     return 2;
1452 }
1453 
1454 static int req_check_len(int len, int n_min, int n_max)
1455 {
1456     if (n_min > 0 && len < n_min) {
1457         BIO_printf(bio_err,
1458                    "String too short, must be at least %d bytes long\n", n_min);
1459         return 0;
1460     }
1461     if (n_max >= 0 && len > n_max) {
1462         BIO_printf(bio_err,
1463                    "String too long, must be at most %d bytes long\n", n_max);
1464         return 0;
1465     }
1466     return 1;
1467 }
1468 
1469 /* Check if the end of a string matches 'end' */
1470 static int check_end(const char *str, const char *end)
1471 {
1472     size_t elen, slen;
1473     const char *tmp;
1474 
1475     elen = strlen(end);
1476     slen = strlen(str);
1477     if (elen > slen)
1478         return 1;
1479     tmp = str + slen - elen;
1480     return strcmp(tmp, end);
1481 }
1482 
1483 /*
1484  * Merge the two strings together into the result buffer checking for
1485  * overflow and producing an error message if there is.
1486  */
1487 static int join(char buf[], size_t buf_size, const char *name,
1488                 const char *tail, const char *desc)
1489 {
1490     const size_t name_len = strlen(name), tail_len = strlen(tail);
1491 
1492     if (name_len + tail_len + 1 > buf_size) {
1493         BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1494         return 0;
1495     }
1496     memcpy(buf, name, name_len);
1497     memcpy(buf + name_len, tail, tail_len + 1);
1498     return 1;
1499 }
1500 
1501 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1502                                     char **pkeytype, long *pkeylen,
1503                                     ENGINE *keygen_engine)
1504 {
1505     EVP_PKEY_CTX *gctx = NULL;
1506     EVP_PKEY *param = NULL;
1507     long keylen = -1;
1508     BIO *pbio = NULL;
1509     const char *keytype = NULL;
1510     size_t keytypelen = 0;
1511     int expect_paramfile = 0;
1512     const char *paramfile = NULL;
1513 
1514     /* Treat the first part of gstr, and only that */
1515     if (gstr == NULL) {
1516         /*
1517          * Special case: when no string given, default to RSA and the
1518          * key length given by |*pkeylen|.
1519          */
1520         keytype = "RSA";
1521         keylen = *pkeylen;
1522     } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1523         /* Special case: only keylength given from string, so default to RSA */
1524         keytype = "RSA";
1525         /* The second part treatment will do the rest */
1526     } else {
1527         const char *p = strchr(gstr, ':');
1528         int len;
1529 
1530         if (p != NULL)
1531             len = p - gstr;
1532         else
1533             len = strlen(gstr);
1534 
1535         if (strncmp(gstr, "param", len) == 0) {
1536             expect_paramfile = 1;
1537             if (p == NULL) {
1538                 BIO_printf(bio_err,
1539                            "Parameter file requested but no path given: %s\n",
1540                            gstr);
1541                 return NULL;
1542             }
1543         } else {
1544             keytype = gstr;
1545             keytypelen = len;
1546         }
1547 
1548         if (p != NULL)
1549             gstr = gstr + len + 1;
1550         else
1551             gstr = NULL;
1552     }
1553 
1554     /* Treat the second part of gstr, if there is one */
1555     if (gstr != NULL) {
1556         /* If the second part starts with a digit, we assume it's a size */
1557         if (!expect_paramfile && gstr[0] >= '0' && gstr[0] <= '9')
1558             keylen = atol(gstr);
1559         else
1560             paramfile = gstr;
1561     }
1562 
1563     if (paramfile != NULL) {
1564         pbio = BIO_new_file(paramfile, "r");
1565         if (pbio == NULL) {
1566             BIO_printf(bio_err, "Cannot open parameter file %s\n", paramfile);
1567             return NULL;
1568         }
1569         param = PEM_read_bio_Parameters(pbio, NULL);
1570 
1571         if (param == NULL) {
1572             X509 *x;
1573 
1574             (void)BIO_reset(pbio);
1575             x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1576             if (x != NULL) {
1577                 param = X509_get_pubkey(x);
1578                 X509_free(x);
1579             }
1580         }
1581 
1582         BIO_free(pbio);
1583 
1584         if (param == NULL) {
1585             BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1586             return NULL;
1587         }
1588         if (keytype == NULL) {
1589             keytype = EVP_PKEY_get0_type_name(param);
1590             if (keytype == NULL) {
1591                 EVP_PKEY_free(param);
1592                 BIO_puts(bio_err, "Unable to determine key type\n");
1593                 return NULL;
1594             }
1595         }
1596     }
1597 
1598     if (keytypelen > 0)
1599         *pkeytype = OPENSSL_strndup(keytype, keytypelen);
1600     else
1601         *pkeytype = OPENSSL_strdup(keytype);
1602 
1603     if (*pkeytype == NULL) {
1604         BIO_printf(bio_err, "Out of memory\n");
1605         EVP_PKEY_free(param);
1606         return NULL;
1607     }
1608 
1609     if (keylen >= 0)
1610         *pkeylen = keylen;
1611 
1612     if (param != NULL) {
1613         if (!EVP_PKEY_is_a(param, *pkeytype)) {
1614             BIO_printf(bio_err, "Key type does not match parameters\n");
1615             EVP_PKEY_free(param);
1616             return NULL;
1617         }
1618 
1619         if (keygen_engine != NULL)
1620             gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1621         else
1622             gctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
1623                                               param, app_get0_propq());
1624         *pkeylen = EVP_PKEY_get_bits(param);
1625         EVP_PKEY_free(param);
1626     } else {
1627         if (keygen_engine != NULL) {
1628             int pkey_id = get_legacy_pkey_id(app_get0_libctx(), *pkeytype,
1629                                              keygen_engine);
1630 
1631             if (pkey_id != NID_undef)
1632                 gctx = EVP_PKEY_CTX_new_id(pkey_id, keygen_engine);
1633         } else {
1634             gctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(),
1635                                               *pkeytype, app_get0_propq());
1636         }
1637     }
1638 
1639     if (gctx == NULL) {
1640         BIO_puts(bio_err, "Error allocating keygen context\n");
1641         return NULL;
1642     }
1643 
1644     if (EVP_PKEY_keygen_init(gctx) <= 0) {
1645         BIO_puts(bio_err, "Error initializing keygen context\n");
1646         EVP_PKEY_CTX_free(gctx);
1647         return NULL;
1648     }
1649     if (keylen == -1 && (EVP_PKEY_CTX_is_a(gctx, "RSA")
1650         || EVP_PKEY_CTX_is_a(gctx, "RSA-PSS")))
1651         keylen = *pkeylen;
1652 
1653     if (keylen != -1) {
1654         OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
1655         size_t bits = keylen;
1656 
1657         params[0] =
1658             OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_BITS, &bits);
1659         if (EVP_PKEY_CTX_set_params(gctx, params) <= 0) {
1660             BIO_puts(bio_err, "Error setting keysize\n");
1661             EVP_PKEY_CTX_free(gctx);
1662             return NULL;
1663         }
1664     }
1665 
1666     return gctx;
1667 }
1668 
1669 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1670 {
1671     char c = '*';
1672     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1673     int p;
1674     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1675     if (p == 0)
1676         c = '.';
1677     if (p == 1)
1678         c = '+';
1679     if (p == 2)
1680         c = '*';
1681     if (p == 3)
1682         c = '\n';
1683     BIO_write(b, &c, 1);
1684     (void)BIO_flush(b);
1685     return 1;
1686 }
1687