req: Do not warn about using stdin when generating new request
[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 (default stdin)"},
107     {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
108     {"verify", OPT_VERIFY, '-', "Verify self-signature on the request"},
109
110     OPT_SECTION("Certificate"),
111     {"new", OPT_NEW, '-', "New request"},
112     {"config", OPT_CONFIG, '<', "Request template file"},
113     {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
114     {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
115     {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
116     {"reqopt", OPT_REQOPT, 's', "Various request text options"},
117     {"text", OPT_TEXT, '-', "Text form of request"},
118     {"x509", OPT_X509, '-',
119      "Output an X.509 certificate structure instead of a cert request"},
120     {"CA", OPT_CA, '<', "Issuer cert to use for signing a cert, implies -x509"},
121     {"CAkey", OPT_CAKEY, 's',
122      "Issuer private key to use with -CA; default is -CA arg"},
123     {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
124     {"subj", OPT_SUBJ, 's', "Set or modify subject of request or cert"},
125     {"subject", OPT_SUBJECT, '-',
126      "Print the subject of the output request or cert"},
127     {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
128      "Deprecated; multi-valued RDNs support is always on."},
129     {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
130     {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
131     {"copy_extensions", OPT_COPY_EXTENSIONS, 's',
132      "copy extensions from request when using -x509"},
133     {"addext", OPT_ADDEXT, 's',
134      "Additional cert extension key=value pair (may be given more than once)"},
135     {"extensions", OPT_EXTENSIONS, 's',
136      "Cert extension section (override value in config file)"},
137     {"reqexts", OPT_REQEXTS, 's',
138      "Request extension section (override value in config file)"},
139     {"precert", OPT_PRECERT, '-', "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     {"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             gen_x509 = 1;
410             break;
411         case OPT_CAKEY:
412             CAkeyfile = opt_arg();
413             break;
414         case OPT_DAYS:
415             days = atoi(opt_arg());
416             if (days < -1) {
417                 BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n",
418                            prog);
419                 goto end;
420             }
421             break;
422         case OPT_SET_SERIAL:
423             if (serial != NULL) {
424                 BIO_printf(bio_err, "Serial number supplied twice\n");
425                 goto opthelp;
426             }
427             serial = s2i_ASN1_INTEGER(NULL, opt_arg());
428             if (serial == NULL)
429                 goto opthelp;
430             break;
431         case OPT_SUBJECT:
432             subject = 1;
433             break;
434         case OPT_SUBJ:
435             subj = opt_arg();
436             break;
437         case OPT_MULTIVALUE_RDN:
438             /* obsolete */
439             break;
440         case OPT_COPY_EXTENSIONS:
441             if (!set_ext_copy(&ext_copy, opt_arg())) {
442                 BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n",
443                            opt_arg());
444                 goto end;
445             }
446             break;
447         case OPT_ADDEXT:
448             p = opt_arg();
449             if (addexts == NULL) {
450                 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
451                 addext_bio = BIO_new(BIO_s_mem());
452                 if (addexts == NULL || addext_bio == NULL)
453                     goto end;
454             }
455             i = duplicated(addexts, p);
456             if (i == 1) {
457                 BIO_printf(bio_err, "Duplicate extension: %s\n", p);
458                 goto opthelp;
459             }
460             if (i < 0 || BIO_printf(addext_bio, "%s\n", p) < 0)
461                 goto end;
462             break;
463         case OPT_EXTENSIONS:
464             extensions = opt_arg();
465             break;
466         case OPT_REQEXTS:
467             req_exts = opt_arg();
468             break;
469         case OPT_PRECERT:
470             newreq = precert = 1;
471             break;
472         case OPT_MD:
473             digest = opt_unknown();
474             break;
475         }
476     }
477
478     /* No extra arguments. */
479     argc = opt_num_rest();
480     if (argc != 0)
481         goto opthelp;
482
483     if (!app_RAND_load())
484         goto end;
485
486     if (!gen_x509) {
487         if (days != UNSET_DAYS)
488             BIO_printf(bio_err, "Ignoring -days without -x509; not generating a certificate\n");
489         if (ext_copy == EXT_COPY_NONE)
490             BIO_printf(bio_err, "Ignoring -copy_extensions 'none' when -x509 is not given\n");
491     }
492     if (infile == NULL) {
493         if (gen_x509)
494             newreq = 1;
495         else if (!newreq)
496             BIO_printf(bio_err,
497                        "Warning: Will read cert request from stdin since no -in option is given\n");
498     }
499
500     if (!app_passwd(passargin, passargout, &passin, &passout)) {
501         BIO_printf(bio_err, "Error getting passwords\n");
502         goto end;
503     }
504
505     if ((req_conf = app_load_config_verbose(template, verbose)) == NULL)
506         goto end;
507     if (addext_bio != NULL) {
508         if (verbose)
509             BIO_printf(bio_err,
510                        "Using additional configuration from -addext options\n");
511         if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
512             goto end;
513     }
514     if (template != default_config_file && !app_load_modules(req_conf))
515         goto end;
516
517     if (req_conf != NULL) {
518         p = NCONF_get_string(req_conf, NULL, "oid_file");
519         if (p == NULL)
520             ERR_clear_error();
521         if (p != NULL) {
522             BIO *oid_bio = BIO_new_file(p, "r");
523
524             if (oid_bio == NULL) {
525                 if (verbose)
526                     BIO_printf(bio_err,
527                                "Problems opening '%s' for extra OIDs\n", p);
528             } else {
529                 OBJ_create_objects(oid_bio);
530                 BIO_free(oid_bio);
531             }
532         }
533     }
534     if (!add_oid_section(req_conf))
535         goto end;
536
537     /* Check that any specified digest is fetchable */
538     if (digest != NULL) {
539         if (!opt_md(digest, &md)) {
540             ERR_clear_error();
541             goto opthelp;
542         }
543         EVP_MD_free(md);
544     } else {
545         /* No digest specified, default to configuration */
546         p = NCONF_get_string(req_conf, section, "default_md");
547         if (p == NULL)
548             ERR_clear_error();
549         else
550             digest = p;
551     }
552
553     if (extensions == NULL) {
554         extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
555         if (extensions == NULL)
556             ERR_clear_error();
557     }
558     if (extensions != NULL) {
559         /* Check syntax of 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, extensions, NULL)) {
565             BIO_printf(bio_err,
566                        "Error checking x509 extension section %s\n",
567                        extensions);
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             NCONF_get_string(req_conf, section, "input_password");
586         if (passin == NULL)
587             ERR_clear_error();
588     }
589
590     if (passout == NULL) {
591         passout = nofree_passout =
592             NCONF_get_string(req_conf, section, "output_password");
593         if (passout == NULL)
594             ERR_clear_error();
595     }
596
597     p = NCONF_get_string(req_conf, section, STRING_MASK);
598     if (p == NULL)
599         ERR_clear_error();
600
601     if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
602         BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
603         goto end;
604     }
605
606     if (chtype != MBSTRING_UTF8) {
607         p = NCONF_get_string(req_conf, section, UTF8_IN);
608         if (p == NULL)
609             ERR_clear_error();
610         else if (strcmp(p, "yes") == 0)
611             chtype = MBSTRING_UTF8;
612     }
613
614     if (req_exts == NULL) {
615         req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
616         if (req_exts == NULL)
617             ERR_clear_error();
618     }
619     if (req_exts != NULL) {
620         /* Check syntax of file */
621         X509V3_CTX ctx;
622
623         X509V3_set_ctx_test(&ctx);
624         X509V3_set_nconf(&ctx, req_conf);
625         if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
626             BIO_printf(bio_err,
627                        "Error checking request extension section %s\n",
628                        req_exts);
629             goto end;
630         }
631     }
632
633     if (keyfile != NULL) {
634         pkey = load_key(keyfile, keyform, 0, passin, e, "private key");
635         if (pkey == NULL)
636             goto end;
637         app_RAND_load_conf(req_conf, section);
638     }
639     if (keyalg != NULL && pkey != NULL) {
640         BIO_printf(bio_err,
641                    "Warning: Not generating key via given -newkey option since -key is given\n");
642         /* Better throw an error in this case */
643     }
644     if (newreq && pkey == NULL) {
645         app_RAND_load_conf(req_conf, section);
646
647         if (!NCONF_get_number(req_conf, section, BITS, &newkey_len))
648             newkey_len = DEFAULT_KEY_LENGTH;
649
650         genctx = set_keygen_ctx(keyalg, &keyalgstr, &newkey_len, gen_eng);
651         if (genctx == NULL)
652             goto end;
653
654         if (newkey_len < MIN_KEY_LENGTH
655             && (EVP_PKEY_CTX_is_a(genctx, "RSA")
656                 || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")
657                 || EVP_PKEY_CTX_is_a(genctx, "DSA"))) {
658             BIO_printf(bio_err, "Private key length too short, needs to be at least %d bits, not %ld.\n",
659                        MIN_KEY_LENGTH, newkey_len);
660             goto end;
661         }
662
663         if (newkey_len > OPENSSL_RSA_MAX_MODULUS_BITS
664             && (EVP_PKEY_CTX_is_a(genctx, "RSA")
665                 || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")))
666             BIO_printf(bio_err,
667                        "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
668                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
669                        OPENSSL_RSA_MAX_MODULUS_BITS, newkey_len);
670
671 #ifndef OPENSSL_NO_DSA
672         if (EVP_PKEY_CTX_is_a(genctx, "DSA")
673                 && newkey_len > OPENSSL_DSA_MAX_MODULUS_BITS)
674             BIO_printf(bio_err,
675                        "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
676                        "         Your key size is %ld! Larger key size may behave not as expected.\n",
677                        OPENSSL_DSA_MAX_MODULUS_BITS, newkey_len);
678 #endif
679
680         if (pkeyopts != NULL) {
681             char *genopt;
682             for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
683                 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
684                 if (pkey_ctrl_string(genctx, genopt) <= 0) {
685                     BIO_printf(bio_err, "Key parameter error \"%s\"\n", genopt);
686                     goto end;
687                 }
688             }
689         }
690
691         EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
692         EVP_PKEY_CTX_set_app_data(genctx, bio_err);
693
694         pkey = app_keygen(genctx, keyalgstr, newkey_len, verbose);
695
696         EVP_PKEY_CTX_free(genctx);
697         genctx = NULL;
698     }
699     if (keyout == NULL && keyfile == NULL) {
700         keyout = NCONF_get_string(req_conf, section, KEYFILE);
701         if (keyout == NULL)
702             ERR_clear_error();
703     }
704
705     if (pkey != NULL && (keyfile == NULL || keyout != NULL)) {
706         if (verbose) {
707             BIO_printf(bio_err, "Writing private key to ");
708             if (keyout == NULL)
709                 BIO_printf(bio_err, "stdout\n");
710             else
711                 BIO_printf(bio_err, "'%s'\n", keyout);
712         }
713         out = bio_open_owner(keyout, outformat, newreq);
714         if (out == NULL)
715             goto end;
716
717         p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
718         if (p == NULL) {
719             ERR_clear_error();
720             p = NCONF_get_string(req_conf, section, "encrypt_key");
721             if (p == NULL)
722                 ERR_clear_error();
723         }
724         if ((p != NULL) && (strcmp(p, "no") == 0))
725             cipher = NULL;
726         if (noenc)
727             cipher = NULL;
728
729         i = 0;
730  loop:
731         if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
732                                       NULL, 0, NULL, passout)) {
733             if ((ERR_GET_REASON(ERR_peek_error()) ==
734                  PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
735                 ERR_clear_error();
736                 i++;
737                 goto loop;
738             }
739             goto end;
740         }
741         BIO_free(out);
742         out = NULL;
743         BIO_printf(bio_err, "-----\n");
744     }
745
746     /*
747      * subj is expected to be in the format /type0=value0/type1=value1/type2=...
748      * where characters may be escaped by \
749      */
750     if (subj != NULL
751             && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
752         goto end;
753
754     if (!newreq) {
755         if (keyfile != NULL)
756             BIO_printf(bio_err,
757                        "Warning: Not placing -key in cert or request since request is used\n");
758         req = load_csr(infile /* if NULL, reads from stdin */,
759                        informat, "X509 request");
760         if (req == NULL)
761             goto end;
762     } else if (infile != NULL) {
763         BIO_printf(bio_err,
764                    "Warning: Ignoring -in option since -new or -newkey or -precert is given\n");
765         /* Better throw an error in this case, as done in the x509 app */
766     }
767
768     if (CAkeyfile == NULL)
769         CAkeyfile = CAfile;
770     if (CAkeyfile != NULL) {
771         if (CAfile == NULL) {
772             BIO_printf(bio_err,
773                        "Warning: Ignoring -CAkey option since no -CA option is given\n");
774         } else {
775             if ((CAkey = load_key(CAkeyfile, FORMAT_UNDEF,
776                                   0, passin, e,
777                                   CAkeyfile != CAfile
778                                   ? "issuer private key from -CAkey arg"
779                                   : "issuer private key from -CA arg")) == NULL)
780                 goto end;
781         }
782     }
783     if (CAfile != NULL) {
784         if ((CAcert = load_cert_pass(CAfile, FORMAT_UNDEF, 1, passin,
785                                      "issuer cert from -CA arg")) == NULL)
786             goto end;
787         if (!X509_check_private_key(CAcert, CAkey)) {
788             BIO_printf(bio_err,
789                        "Issuer CA certificate and key do not match\n");
790             goto end;
791         }
792     }
793     if (newreq || gen_x509) {
794         if (pkey == NULL /* can happen only if !newreq */) {
795             BIO_printf(bio_err, "Must provide a signature key using -key\n");
796             goto end;
797         }
798
799         if (req == NULL) {
800             req = X509_REQ_new_ex(app_get0_libctx(), app_get0_propq());
801             if (req == NULL) {
802                 goto end;
803             }
804
805             if (!make_REQ(req, pkey, fsubj, multirdn, !gen_x509, chtype)){
806                 BIO_printf(bio_err, "Error making certificate request\n");
807                 goto end;
808             }
809             /* Note that -x509 can take over -key and -subj option values. */
810         }
811         if (gen_x509) {
812             EVP_PKEY *pub_key = X509_REQ_get0_pubkey(req);
813             EVP_PKEY *issuer_key = CAcert != NULL ? CAkey : pkey;
814             X509V3_CTX ext_ctx;
815             X509_NAME *issuer = CAcert != NULL ? X509_get_subject_name(CAcert) :
816                 X509_REQ_get_subject_name(req);
817             X509_NAME *n_subj = fsubj != NULL ? fsubj :
818                 X509_REQ_get_subject_name(req);
819
820             if (CAcert != NULL && keyfile != NULL)
821                 BIO_printf(bio_err,
822                            "Warning: Not using -key or -newkey for signing since -CA option is given\n");
823
824             if ((new_x509 = X509_new_ex(app_get0_libctx(),
825                                         app_get0_propq())) == NULL)
826                 goto end;
827
828             if (serial != NULL) {
829                 if (!X509_set_serialNumber(new_x509, serial))
830                     goto end;
831             } else {
832                 if (!rand_serial(NULL, X509_get_serialNumber(new_x509)))
833                     goto end;
834             }
835
836             if (!X509_set_issuer_name(new_x509, issuer))
837                 goto end;
838             if (days == UNSET_DAYS) {
839                 days = DEFAULT_DAYS;
840             }
841             if (!set_cert_times(new_x509, NULL, NULL, days))
842                 goto end;
843             if (!X509_set_subject_name(new_x509, n_subj))
844                 goto end;
845             if (!pub_key || !X509_set_pubkey(new_x509, pub_key))
846                 goto end;
847             if (ext_copy == EXT_COPY_UNSET) {
848                 if (infile != NULL)
849                     BIO_printf(bio_err, "Warning: No -copy_extensions given; ignoring any extensions in the request\n");
850             } else if (!copy_extensions(new_x509, req, ext_copy)) {
851                 BIO_printf(bio_err, "Error copying extensions from request\n");
852                 goto end;
853             }
854
855             /* Set up V3 context struct */
856             X509V3_set_ctx(&ext_ctx, CAcert != NULL ? CAcert : new_x509,
857                            new_x509, NULL, NULL, X509V3_CTX_REPLACE);
858             /* prepare fallback for AKID, but only if issuer cert == new_x509 */
859             if (CAcert == NULL) {
860                 if (!X509V3_set_issuer_pkey(&ext_ctx, issuer_key))
861                     goto end;
862                 ERR_set_mark();
863                 if (!X509_check_private_key(new_x509, issuer_key))
864                     BIO_printf(bio_err,
865                                "Warning: Signature key and public key of cert do not match\n");
866                 ERR_pop_to_mark();
867             }
868             X509V3_set_nconf(&ext_ctx, req_conf);
869
870             /* Add extensions */
871             if (extensions != NULL
872                     && !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extensions,
873                                              new_x509)) {
874                 BIO_printf(bio_err, "Error adding x509 extensions from section %s\n",
875                            extensions);
876                 goto end;
877             }
878             if (addext_conf != NULL
879                 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
880                                          new_x509)) {
881                 BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
882                 goto end;
883             }
884
885             /* If a pre-cert was requested, we need to add a poison extension */
886             if (precert) {
887                 if (X509_add1_ext_i2d(new_x509, NID_ct_precert_poison,
888                                       NULL, 1, 0) != 1) {
889                     BIO_printf(bio_err, "Error adding poison extension\n");
890                     goto end;
891                 }
892             }
893
894             i = do_X509_sign(new_x509, issuer_key, digest, sigopts, &ext_ctx);
895             if (!i)
896                 goto end;
897         } else {
898             X509V3_CTX ext_ctx;
899
900             if (precert) {
901                 BIO_printf(bio_err,
902                            "Warning: Ignoring -precert flag since no cert is produced\n");
903             }
904             /* Set up V3 context struct */
905             X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
906             X509V3_set_nconf(&ext_ctx, req_conf);
907
908             /* Add extensions */
909             if (req_exts != NULL
910                 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
911                                              req_exts, req)) {
912                 BIO_printf(bio_err, "Error adding request extensions from section %s\n",
913                            req_exts);
914                 goto end;
915             }
916             if (addext_conf != NULL
917                 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
918                                              req)) {
919                 BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
920                 goto end;
921             }
922             i = do_X509_REQ_sign(req, pkey, digest, sigopts);
923             if (!i)
924                 goto end;
925         }
926     }
927
928     if (subj != NULL && !newreq && !gen_x509) {
929         if (verbose) {
930             BIO_printf(out, "Modifying subject of certificate request\n");
931             print_name(out, "Old subject=", X509_REQ_get_subject_name(req));
932         }
933
934         if (!X509_REQ_set_subject_name(req, fsubj)) {
935             BIO_printf(bio_err, "Error modifying subject of certificate request\n");
936             goto end;
937         }
938
939         if (verbose) {
940             print_name(out, "New subject=", X509_REQ_get_subject_name(req));
941         }
942     }
943
944     if (verify) {
945         EVP_PKEY *tpubkey = pkey;
946
947         if (tpubkey == NULL) {
948             tpubkey = X509_REQ_get0_pubkey(req);
949             if (tpubkey == NULL)
950                 goto end;
951         }
952
953         i = do_X509_REQ_verify(req, tpubkey, vfyopts);
954
955         if (i < 0)
956             goto end;
957         if (i == 0)
958             BIO_printf(bio_err, "Certificate request self-signature verify failure\n");
959         else /* i > 0 */
960             BIO_printf(bio_err, "Certificate request self-signature verify OK\n");
961     }
962
963     if (noout && !text && !modulus && !subject && !pubkey) {
964         ret = 0;
965         goto end;
966     }
967
968     out = bio_open_default(outfile,
969                            keyout != NULL && outfile != NULL &&
970                            strcmp(keyout, outfile) == 0 ? 'a' : 'w',
971                            outformat);
972     if (out == NULL)
973         goto end;
974
975     if (pubkey) {
976         EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
977
978         if (tpubkey == NULL) {
979             BIO_printf(bio_err, "Error getting public key\n");
980             goto end;
981         }
982         PEM_write_bio_PUBKEY(out, tpubkey);
983     }
984
985     if (text) {
986         if (gen_x509)
987             ret = X509_print_ex(out, new_x509, get_nameopt(), reqflag);
988         else
989             ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
990
991         if (ret == 0) {
992             if (gen_x509)
993                 BIO_printf(bio_err, "Error printing certificate\n");
994             else
995                 BIO_printf(bio_err, "Error printing certificate request\n");
996             goto end;
997         }
998     }
999
1000     if (subject) {
1001         print_name(out, "subject=", gen_x509
1002                    ? X509_get_subject_name(new_x509)
1003                    : X509_REQ_get_subject_name(req));
1004     }
1005
1006     if (modulus) {
1007         EVP_PKEY *tpubkey;
1008
1009         if (gen_x509)
1010             tpubkey = X509_get0_pubkey(new_x509);
1011         else
1012             tpubkey = X509_REQ_get0_pubkey(req);
1013         if (tpubkey == NULL) {
1014             fprintf(stdout, "Modulus is unavailable\n");
1015             goto end;
1016         }
1017         fprintf(stdout, "Modulus=");
1018         if (EVP_PKEY_is_a(tpubkey, "RSA")) {
1019             BIGNUM *n = NULL;
1020
1021             if (!EVP_PKEY_get_bn_param(tpubkey, "n", &n))
1022                 goto end;
1023             BN_print(out, n);
1024             BN_free(n);
1025         } else {
1026             fprintf(stdout, "Wrong Algorithm type");
1027         }
1028         fprintf(stdout, "\n");
1029     }
1030
1031     if (!noout && !gen_x509) {
1032         if (outformat == FORMAT_ASN1)
1033             i = i2d_X509_REQ_bio(out, req);
1034         else if (newhdr)
1035             i = PEM_write_bio_X509_REQ_NEW(out, req);
1036         else
1037             i = PEM_write_bio_X509_REQ(out, req);
1038         if (!i) {
1039             BIO_printf(bio_err, "Unable to write certificate request\n");
1040             goto end;
1041         }
1042     }
1043     if (!noout && gen_x509 && new_x509 != NULL) {
1044         if (outformat == FORMAT_ASN1)
1045             i = i2d_X509_bio(out, new_x509);
1046         else
1047             i = PEM_write_bio_X509(out, new_x509);
1048         if (!i) {
1049             BIO_printf(bio_err, "Unable to write X509 certificate\n");
1050             goto end;
1051         }
1052     }
1053     ret = 0;
1054  end:
1055     if (ret) {
1056         ERR_print_errors(bio_err);
1057     }
1058     NCONF_free(req_conf);
1059     NCONF_free(addext_conf);
1060     BIO_free(addext_bio);
1061     BIO_free_all(out);
1062     EVP_PKEY_free(pkey);
1063     EVP_PKEY_CTX_free(genctx);
1064     sk_OPENSSL_STRING_free(pkeyopts);
1065     sk_OPENSSL_STRING_free(sigopts);
1066     sk_OPENSSL_STRING_free(vfyopts);
1067     lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
1068     lh_OPENSSL_STRING_free(addexts);
1069 #ifndef OPENSSL_NO_ENGINE
1070     release_engine(gen_eng);
1071 #endif
1072     OPENSSL_free(keyalgstr);
1073     X509_REQ_free(req);
1074     X509_NAME_free(fsubj);
1075     X509_free(new_x509);
1076     X509_free(CAcert);
1077     EVP_PKEY_free(CAkey);
1078     ASN1_INTEGER_free(serial);
1079     release_engine(e);
1080     if (passin != nofree_passin)
1081         OPENSSL_free(passin);
1082     if (passout != nofree_passout)
1083         OPENSSL_free(passout);
1084     return ret;
1085 }
1086
1087 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
1088                     int multirdn, int attribs, unsigned long chtype)
1089 {
1090     int ret = 0, i;
1091     char no_prompt = 0;
1092     STACK_OF(CONF_VALUE) *dn_sk = NULL, *attr_sk = NULL;
1093     char *tmp, *dn_sect, *attr_sect;
1094
1095     tmp = NCONF_get_string(req_conf, section, PROMPT);
1096     if (tmp == NULL)
1097         ERR_clear_error();
1098     if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1099         no_prompt = 1;
1100
1101     dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1102     if (dn_sect == NULL) {
1103         ERR_clear_error();
1104     } else {
1105         dn_sk = NCONF_get_section(req_conf, dn_sect);
1106         if (dn_sk == NULL) {
1107             BIO_printf(bio_err, "Unable to get '%s' section\n", dn_sect);
1108             goto err;
1109         }
1110     }
1111
1112     attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1113     if (attr_sect == NULL) {
1114         ERR_clear_error();
1115     } else {
1116         attr_sk = NCONF_get_section(req_conf, attr_sect);
1117         if (attr_sk == NULL) {
1118             BIO_printf(bio_err, "Unable to get '%s' section\n", attr_sect);
1119             goto err;
1120         }
1121     }
1122
1123     /* so far there is only version 1 */
1124     if (!X509_REQ_set_version(req, X509_REQ_VERSION_1))
1125         goto err;
1126
1127     if (fsubj != NULL)
1128         i = X509_REQ_set_subject_name(req, fsubj);
1129     else if (no_prompt)
1130         i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1131     else
1132         i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1133                         chtype);
1134     if (!i)
1135         goto err;
1136
1137     if (!X509_REQ_set_pubkey(req, pkey))
1138         goto err;
1139
1140     ret = 1;
1141  err:
1142     return ret;
1143 }
1144
1145 static int prompt_info(X509_REQ *req,
1146                        STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1147                        STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1148                        int attribs, unsigned long chtype)
1149 {
1150     int i;
1151     char *p, *q;
1152     char buf[100];
1153     int nid, mval;
1154     long n_min, n_max;
1155     char *type, *value;
1156     const char *def;
1157     CONF_VALUE *v;
1158     X509_NAME *subj = X509_REQ_get_subject_name(req);
1159
1160     if (!batch) {
1161         BIO_printf(bio_err,
1162                    "You are about to be asked to enter information that will be incorporated\n");
1163         BIO_printf(bio_err, "into your certificate request.\n");
1164         BIO_printf(bio_err,
1165                    "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1166         BIO_printf(bio_err,
1167                    "There are quite a few fields but you can leave some blank\n");
1168         BIO_printf(bio_err,
1169                    "For some fields there will be a default value,\n");
1170         BIO_printf(bio_err,
1171                    "If you enter '.', the field will be left blank.\n");
1172         BIO_printf(bio_err, "-----\n");
1173     }
1174
1175     if (sk_CONF_VALUE_num(dn_sk)) {
1176         i = -1;
1177  start:
1178         for (;;) {
1179             i++;
1180             if (sk_CONF_VALUE_num(dn_sk) <= i)
1181                 break;
1182
1183             v = sk_CONF_VALUE_value(dn_sk, i);
1184             p = q = NULL;
1185             type = v->name;
1186             if (!check_end(type, "_min") || !check_end(type, "_max") ||
1187                 !check_end(type, "_default") || !check_end(type, "_value"))
1188                 continue;
1189             /*
1190              * Skip past any leading X. X: X, etc to allow for multiple
1191              * instances
1192              */
1193             for (p = v->name; *p; p++)
1194                 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1195                     p++;
1196                     if (*p)
1197                         type = p;
1198                     break;
1199                 }
1200             if (*type == '+') {
1201                 mval = -1;
1202                 type++;
1203             } else {
1204                 mval = 0;
1205             }
1206             /* If OBJ not recognised ignore it */
1207             if ((nid = OBJ_txt2nid(type)) == NID_undef)
1208                 goto start;
1209             if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1210                 return 0;
1211             if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1212                 ERR_clear_error();
1213                 def = "";
1214             }
1215
1216             if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1217                 return 0;
1218             if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1219                 ERR_clear_error();
1220                 value = NULL;
1221             }
1222
1223             if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1224                 return 0;
1225             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1226                 ERR_clear_error();
1227                 n_min = -1;
1228             }
1229
1230             if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1231                 return 0;
1232             if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1233                 ERR_clear_error();
1234                 n_max = -1;
1235             }
1236
1237             if (!add_DN_object(subj, v->value, def, value, nid,
1238                                n_min, n_max, chtype, mval))
1239                 return 0;
1240         }
1241         if (X509_NAME_entry_count(subj) == 0) {
1242             BIO_printf(bio_err, "Error: No objects specified in config file\n");
1243             return 0;
1244         }
1245
1246         if (attribs) {
1247             if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1248                 && (!batch)) {
1249                 BIO_printf(bio_err,
1250                            "\nPlease enter the following 'extra' attributes\n");
1251                 BIO_printf(bio_err,
1252                            "to be sent with your certificate request\n");
1253             }
1254
1255             i = -1;
1256  start2:
1257             for (;;) {
1258                 i++;
1259                 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1260                     break;
1261
1262                 v = sk_CONF_VALUE_value(attr_sk, i);
1263                 type = v->name;
1264                 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1265                     goto start2;
1266
1267                 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1268                     return 0;
1269                 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1270                     == NULL) {
1271                     ERR_clear_error();
1272                     def = "";
1273                 }
1274
1275                 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1276                     return 0;
1277                 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1278                     == NULL) {
1279                     ERR_clear_error();
1280                     value = NULL;
1281                 }
1282
1283                 if (!join(buf, sizeof(buf), type, "_min", "Name"))
1284                     return 0;
1285                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1286                     ERR_clear_error();
1287                     n_min = -1;
1288                 }
1289
1290                 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1291                     return 0;
1292                 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1293                     ERR_clear_error();
1294                     n_max = -1;
1295                 }
1296
1297                 if (!add_attribute_object(req,
1298                                           v->value, def, value, nid, n_min,
1299                                           n_max, chtype))
1300                     return 0;
1301             }
1302         }
1303     } else {
1304         BIO_printf(bio_err, "No template, please set one up.\n");
1305         return 0;
1306     }
1307
1308     return 1;
1309
1310 }
1311
1312 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1313                      STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1314                      unsigned long chtype)
1315 {
1316     int i, spec_char, plus_char;
1317     char *p, *q;
1318     char *type;
1319     CONF_VALUE *v;
1320     X509_NAME *subj;
1321
1322     subj = X509_REQ_get_subject_name(req);
1323
1324     for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1325         int mval;
1326         v = sk_CONF_VALUE_value(dn_sk, i);
1327         p = q = NULL;
1328         type = v->name;
1329         /*
1330          * Skip past any leading X. X: X, etc to allow for multiple instances
1331          */
1332         for (p = v->name; *p; p++) {
1333 #ifndef CHARSET_EBCDIC
1334             spec_char = (*p == ':' || *p == ',' || *p == '.');
1335 #else
1336             spec_char = (*p == os_toascii[':'] || *p == os_toascii[',']
1337                          || *p == os_toascii['.']);
1338 #endif
1339             if (spec_char) {
1340                 p++;
1341                 if (*p)
1342                     type = p;
1343                 break;
1344             }
1345         }
1346 #ifndef CHARSET_EBCDIC
1347         plus_char = (*type == '+');
1348 #else
1349         plus_char = (*type == os_toascii['+']);
1350 #endif
1351         if (plus_char) {
1352             type++;
1353             mval = -1;
1354         } else {
1355             mval = 0;
1356         }
1357         if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1358                                         (unsigned char *)v->value, -1, -1,
1359                                         mval))
1360             return 0;
1361
1362     }
1363
1364     if (!X509_NAME_entry_count(subj)) {
1365         BIO_printf(bio_err, "Error: No objects specified in config file\n");
1366         return 0;
1367     }
1368     if (attribs) {
1369         for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1370             v = sk_CONF_VALUE_value(attr_sk, i);
1371             if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1372                                            (unsigned char *)v->value, -1))
1373                 return 0;
1374         }
1375     }
1376     return 1;
1377 }
1378
1379 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1380                          char *value, int nid, int n_min, int n_max,
1381                          unsigned long chtype, int mval)
1382 {
1383     int ret = 0;
1384     char buf[1024];
1385
1386     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1387                      "DN value", "DN default");
1388     if ((ret == 0) || (ret == 1))
1389         return ret;
1390     ret = 1;
1391
1392     if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1393                                     (unsigned char *)buf, -1, -1, mval))
1394         ret = 0;
1395
1396     return ret;
1397 }
1398
1399 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1400                                 char *value, int nid, int n_min,
1401                                 int n_max, unsigned long chtype)
1402 {
1403     int ret = 0;
1404     char buf[1024];
1405
1406     ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1407                      "Attribute value", "Attribute default");
1408     if ((ret == 0) || (ret == 1))
1409         return ret;
1410     ret = 1;
1411
1412     if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1413                                    (unsigned char *)buf, -1)) {
1414         BIO_printf(bio_err, "Error adding attribute\n");
1415         ret = 0;
1416     }
1417
1418     return ret;
1419 }
1420
1421 static int build_data(char *text, const char *def, char *value,
1422                       int n_min, int n_max, char *buf, const int buf_size,
1423                       const char *desc1, const char *desc2)
1424 {
1425     int i;
1426  start:
1427     if (!batch)
1428         BIO_printf(bio_err, "%s [%s]:", text, def);
1429     (void)BIO_flush(bio_err);
1430     if (value != NULL) {
1431         if (!join(buf, buf_size, value, "\n", desc1))
1432             return 0;
1433         BIO_printf(bio_err, "%s\n", value);
1434     } else {
1435         buf[0] = '\0';
1436         if (!batch) {
1437             if (!fgets(buf, buf_size, stdin))
1438                 return 0;
1439         } else {
1440             buf[0] = '\n';
1441             buf[1] = '\0';
1442         }
1443     }
1444
1445     if (buf[0] == '\0')
1446         return 0;
1447     if (buf[0] == '\n') {
1448         if ((def == NULL) || (def[0] == '\0'))
1449             return 1;
1450         if (!join(buf, buf_size, def, "\n", desc2))
1451             return 0;
1452     } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1453         return 1;
1454     }
1455
1456     i = strlen(buf);
1457     if (buf[i - 1] != '\n') {
1458         BIO_printf(bio_err, "Missing newline at end of input\n");
1459         return 0;
1460     }
1461     buf[--i] = '\0';
1462 #ifdef CHARSET_EBCDIC
1463     ebcdic2ascii(buf, buf, i);
1464 #endif
1465     if (!req_check_len(i, n_min, n_max)) {
1466         if (batch || value)
1467             return 0;
1468         goto start;
1469     }
1470     return 2;
1471 }
1472
1473 static int req_check_len(int len, int n_min, int n_max)
1474 {
1475     if (n_min > 0 && len < n_min) {
1476         BIO_printf(bio_err,
1477                    "String too short, must be at least %d bytes long\n", n_min);
1478         return 0;
1479     }
1480     if (n_max >= 0 && len > n_max) {
1481         BIO_printf(bio_err,
1482                    "String too long, must be at most %d bytes long\n", n_max);
1483         return 0;
1484     }
1485     return 1;
1486 }
1487
1488 /* Check if the end of a string matches 'end' */
1489 static int check_end(const char *str, const char *end)
1490 {
1491     size_t elen, slen;
1492     const char *tmp;
1493
1494     elen = strlen(end);
1495     slen = strlen(str);
1496     if (elen > slen)
1497         return 1;
1498     tmp = str + slen - elen;
1499     return strcmp(tmp, end);
1500 }
1501
1502 /*
1503  * Merge the two strings together into the result buffer checking for
1504  * overflow and producing an error message if there is.
1505  */
1506 static int join(char buf[], size_t buf_size, const char *name,
1507                 const char *tail, const char *desc)
1508 {
1509     const size_t name_len = strlen(name), tail_len = strlen(tail);
1510
1511     if (name_len + tail_len + 1 > buf_size) {
1512         BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1513         return 0;
1514     }
1515     memcpy(buf, name, name_len);
1516     memcpy(buf + name_len, tail, tail_len + 1);
1517     return 1;
1518 }
1519
1520 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1521                                     char **pkeytype, long *pkeylen,
1522                                     ENGINE *keygen_engine)
1523 {
1524     EVP_PKEY_CTX *gctx = NULL;
1525     EVP_PKEY *param = NULL;
1526     long keylen = -1;
1527     BIO *pbio = NULL;
1528     const char *keytype = NULL;
1529     size_t keytypelen = 0;
1530     int expect_paramfile = 0;
1531     const char *paramfile = NULL;
1532
1533     /* Treat the first part of gstr, and only that */
1534     if (gstr == NULL) {
1535         /*
1536          * Special case: when no string given, default to RSA and the
1537          * key length given by |*pkeylen|.
1538          */
1539         keytype = "RSA";
1540         keylen = *pkeylen;
1541     } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1542         /* Special case: only keylength given from string, so default to RSA */
1543         keytype = "RSA";
1544         /* The second part treatment will do the rest */
1545     } else {
1546         const char *p = strchr(gstr, ':');
1547         int len;
1548
1549         if (p != NULL)
1550             len = p - gstr;
1551         else
1552             len = strlen(gstr);
1553
1554         if (strncmp(gstr, "param", len) == 0) {
1555             expect_paramfile = 1;
1556             if (p == NULL) {
1557                 BIO_printf(bio_err,
1558                            "Parameter file requested but no path given: %s\n",
1559                            gstr);
1560                 return NULL;
1561             }
1562         } else {
1563             keytype = gstr;
1564             keytypelen = len;
1565         }
1566
1567         if (p != NULL)
1568             gstr = gstr + len + 1;
1569         else
1570             gstr = NULL;
1571     }
1572
1573     /* Treat the second part of gstr, if there is one */
1574     if (gstr != NULL) {
1575         /* If the second part starts with a digit, we assume it's a size */
1576         if (!expect_paramfile && gstr[0] >= '0' && gstr[0] <= '9')
1577             keylen = atol(gstr);
1578         else
1579             paramfile = gstr;
1580     }
1581
1582     if (paramfile != NULL) {
1583         pbio = BIO_new_file(paramfile, "r");
1584         if (pbio == NULL) {
1585             BIO_printf(bio_err, "Cannot open parameter file %s\n", paramfile);
1586             return NULL;
1587         }
1588         param = PEM_read_bio_Parameters(pbio, NULL);
1589
1590         if (param == NULL) {
1591             X509 *x;
1592
1593             (void)BIO_reset(pbio);
1594             x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1595             if (x != NULL) {
1596                 param = X509_get_pubkey(x);
1597                 X509_free(x);
1598             }
1599         }
1600
1601         BIO_free(pbio);
1602
1603         if (param == NULL) {
1604             BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1605             return NULL;
1606         }
1607         if (keytype == NULL) {
1608             keytype = EVP_PKEY_get0_type_name(param);
1609             if (keytype == NULL) {
1610                 EVP_PKEY_free(param);
1611                 BIO_puts(bio_err, "Unable to determine key type\n");
1612                 return NULL;
1613             }
1614         }
1615     }
1616
1617     if (keytypelen > 0)
1618         *pkeytype = OPENSSL_strndup(keytype, keytypelen);
1619     else
1620         *pkeytype = OPENSSL_strdup(keytype);
1621     if (keylen >= 0)
1622         *pkeylen = keylen;
1623
1624     if (param != NULL) {
1625         if (!EVP_PKEY_is_a(param, *pkeytype)) {
1626             BIO_printf(bio_err, "Key type does not match parameters\n");
1627             EVP_PKEY_free(param);
1628             return NULL;
1629         }
1630
1631         if (keygen_engine != NULL)
1632             gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1633         else
1634             gctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
1635                                               param, app_get0_propq());
1636         *pkeylen = EVP_PKEY_get_bits(param);
1637         EVP_PKEY_free(param);
1638     } else {
1639         if (keygen_engine != NULL) {
1640             int pkey_id = get_legacy_pkey_id(app_get0_libctx(), *pkeytype,
1641                                              keygen_engine);
1642
1643             if (pkey_id != NID_undef)
1644                 gctx = EVP_PKEY_CTX_new_id(pkey_id, keygen_engine);
1645         } else {
1646             gctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(),
1647                                               *pkeytype, app_get0_propq());
1648         }
1649     }
1650
1651     if (gctx == NULL) {
1652         BIO_puts(bio_err, "Error allocating keygen context\n");
1653         return NULL;
1654     }
1655
1656     if (EVP_PKEY_keygen_init(gctx) <= 0) {
1657         BIO_puts(bio_err, "Error initializing keygen context\n");
1658         EVP_PKEY_CTX_free(gctx);
1659         return NULL;
1660     }
1661     if (keylen == -1 && (EVP_PKEY_CTX_is_a(gctx, "RSA")
1662         || EVP_PKEY_CTX_is_a(gctx, "RSA-PSS")))
1663         keylen = *pkeylen;
1664
1665     if (keylen != -1) {
1666         OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
1667         size_t bits = keylen;
1668
1669         params[0] =
1670             OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_BITS, &bits);
1671         if (EVP_PKEY_CTX_set_params(gctx, params) <= 0) {
1672             BIO_puts(bio_err, "Error setting keysize\n");
1673             EVP_PKEY_CTX_free(gctx);
1674             return NULL;
1675         }
1676     }
1677
1678     return gctx;
1679 }
1680
1681 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1682 {
1683     char c = '*';
1684     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1685     int p;
1686     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1687     if (p == 0)
1688         c = '.';
1689     if (p == 1)
1690         c = '+';
1691     if (p == 2)
1692         c = '*';
1693     if (p == 3)
1694         c = '\n';
1695     BIO_write(b, &c, 1);
1696     (void)BIO_flush(b);
1697     return 1;
1698 }