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