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