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