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