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