]> git.ipfire.org Git - thirdparty/openssl.git/blame - apps/lib/apps.c
test/recipes/*.t: setup() doesn't play well with spaces in the argument
[thirdparty/openssl.git] / apps / lib / apps.c
CommitLineData
846e33c7 1/*
065121ff 2 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
a661b653 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
a661b653 8 */
d02b48c6 9
fc7dae52 10#if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
0f113f3e
MC
11/*
12 * On VMS, you need to define this to get the declaration of fileno(). The
13 * value 2 is to make sure no function defined in POSIX-2 is left undefined.
68d39f3c 14 */
0f113f3e 15# define _POSIX_C_SOURCE 2
83d8fa7d 16#endif
75dd6c1a 17
ff215713
P
18#ifndef OPENSSL_NO_ENGINE
19/* We need to use some deprecated APIs */
20# define OPENSSL_SUPPRESS_DEPRECATED
21# include <openssl/engine.h>
22#endif
23
d02b48c6
RE
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
b379fe6c 27#include <sys/types.h>
a412b891
RL
28#ifndef OPENSSL_NO_POSIX_IO
29# include <sys/stat.h>
30# include <fcntl.h>
31#endif
d652a095 32#include <ctype.h>
a1ad253f 33#include <errno.h>
90ae4673
RL
34#include <openssl/err.h>
35#include <openssl/x509.h>
535d79da 36#include <openssl/x509v3.h>
9498dac4 37#include <openssl/http.h>
90ae4673 38#include <openssl/pem.h>
6d382c74 39#include <openssl/store.h>
90ae4673 40#include <openssl/pkcs12.h>
2fe5adc3 41#include <openssl/ui.h>
90ae4673 42#include <openssl/safestack.h>
3a1ee3c1 43#include <openssl/rsa.h>
a7e4ca5b 44#include <openssl/rand.h>
f0eae953 45#include <openssl/bn.h>
7e1b7485 46#include <openssl/ssl.h>
d382e796 47#include <openssl/core_names.h>
0b27381f 48#include "s_apps.h"
d610d27f 49#include "apps.h"
d610d27f 50
a1ad253f
AP
51#ifdef _WIN32
52static int WIN32_rename(const char *from, const char *to);
8cdb993d 53# define rename(from, to) WIN32_rename((from), (to))
a1ad253f
AP
54#endif
55
d0cf719e
DMSP
56#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
57# include <conio.h>
58#endif
59
96d4ec67 60#if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) || defined(__BORLANDC__)
d0cf719e
DMSP
61# define _kbhit kbhit
62#endif
63
15795943
DDO
64static BIO *bio_open_default_(const char *filename, char mode, int format,
65 int quiet);
66
62ca1565
DO
67#define PASS_SOURCE_SIZE_MAX 4
68
852c2ed2 69DEFINE_STACK_OF(CONF)
852c2ed2 70
8ca533e3 71typedef struct {
0f113f3e
MC
72 const char *name;
73 unsigned long flag;
74 unsigned long mask;
8ca533e3
DSH
75} NAME_EX_TBL;
76
0f113f3e
MC
77static int set_table_opts(unsigned long *flags, const char *arg,
78 const NAME_EX_TBL * in_tbl);
79static int set_multi_opts(unsigned long *flags, const char *arg,
80 const NAME_EX_TBL * in_tbl);
d02b48c6 81int app_init(long mesgwin);
0f113f3e 82
7e1b7485 83int chopup_args(ARGS *arg, char *buf)
0f113f3e 84{
7e1b7485 85 int quoted;
4c9b0a03 86 char c = '\0', *p = NULL;
0f113f3e 87
7e1b7485
RS
88 arg->argc = 0;
89 if (arg->size == 0) {
90 arg->size = 20;
b4faea50 91 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
0f113f3e 92 }
0f113f3e 93
7e1b7485
RS
94 for (p = buf;;) {
95 /* Skip whitespace. */
18295f0c 96 while (*p && isspace(_UC(*p)))
0f113f3e 97 p++;
12a765a5 98 if (*p == '\0')
0f113f3e
MC
99 break;
100
101 /* The start of something good :-) */
7e1b7485 102 if (arg->argc >= arg->size) {
7c0ef843 103 char **tmp;
8cdb993d 104
7e1b7485 105 arg->size += 20;
7c0ef843
DSH
106 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
107 if (tmp == NULL)
0f113f3e 108 return 0;
7c0ef843 109 arg->argv = tmp;
0f113f3e 110 }
7e1b7485
RS
111 quoted = *p == '\'' || *p == '"';
112 if (quoted)
113 c = *p++;
114 arg->argv[arg->argc++] = p;
0f113f3e
MC
115
116 /* now look for the end of this */
7e1b7485
RS
117 if (quoted) {
118 while (*p && *p != c)
0f113f3e 119 p++;
7e1b7485 120 *p++ = '\0';
0f113f3e 121 } else {
18295f0c 122 while (*p && !isspace(_UC(*p)))
0f113f3e 123 p++;
7e1b7485
RS
124 if (*p)
125 *p++ = '\0';
0f113f3e 126 }
0f113f3e 127 }
7e1b7485 128 arg->argv[arg->argc] = NULL;
208fb891 129 return 1;
0f113f3e 130}
d02b48c6
RE
131
132#ifndef APP_INIT
6b691a5c 133int app_init(long mesgwin)
0f113f3e 134{
208fb891 135 return 1;
0f113f3e 136}
d02b48c6 137#endif
53b1899e 138
fd3397fc
RL
139int ctx_set_verify_locations(SSL_CTX *ctx,
140 const char *CAfile, int noCAfile,
141 const char *CApath, int noCApath,
142 const char *CAstore, int noCAstore)
7e1b7485 143{
fd3397fc 144 if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
2b6bcb70
MC
145 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
146 return 0;
147 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
148 return 0;
fd3397fc
RL
149 if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
150 return 0;
2b6bcb70
MC
151
152 return 1;
153 }
fd3397fc
RL
154
155 if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
156 return 0;
157 if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
158 return 0;
159 if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
160 return 0;
161 return 1;
7e1b7485
RS
162}
163
b5369582
RP
164#ifndef OPENSSL_NO_CT
165
dd696a55
RP
166int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
167{
2234212c 168 if (path == NULL)
328f36c5 169 return SSL_CTX_set_default_ctlog_list_file(ctx);
dd696a55
RP
170
171 return SSL_CTX_set_ctlog_list_file(ctx, path);
172}
173
b5369582
RP
174#endif
175
b5c4209b
DB
176static unsigned long nmflag = 0;
177static char nmflag_set = 0;
178
179int set_nameopt(const char *arg)
954ef7ef 180{
b5c4209b
DB
181 int ret = set_name_ex(&nmflag, arg);
182
183 if (ret)
184 nmflag_set = 1;
185
186 return ret;
187}
54a656ef 188
b5c4209b
DB
189unsigned long get_nameopt(void)
190{
8cdb993d
DDO
191 return
192 nmflag_set ? nmflag : XN_FLAG_SEP_CPLUS_SPC | ASN1_STRFLGS_UTF8_CONVERT;
b5c4209b 193}
954ef7ef 194
32f7be2a 195void dump_cert_text(BIO *out, X509 *x)
b5c4209b 196{
46a11faf 197 print_name(out, "subject=", X509_get_subject_name(x));
46a11faf 198 print_name(out, "issuer=", X509_get_issuer_name(x));
954ef7ef 199}
a3fe382e 200
229446df
RS
201int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
202{
203 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
204}
205
cc696296 206static char *app_get_pass(const char *arg, int keepbio);
a3fe382e 207
6d382c74
DDO
208char *get_passwd(const char *pass, const char *desc)
209{
210 char *result = NULL;
211
212 if (desc == NULL)
213 desc = "<unknown>";
214 if (!app_passwd(pass, NULL, &result, NULL))
215 BIO_printf(bio_err, "Error getting password for %s\n", desc);
216 if (pass != NULL && result == NULL) {
217 BIO_printf(bio_err,
218 "Trying plain input string (better precede with 'pass:')\n");
219 result = OPENSSL_strdup(pass);
220 if (result == NULL)
8cdb993d
DDO
221 BIO_printf(bio_err,
222 "Out of memory getting password for %s\n", desc);
6d382c74
DDO
223 }
224 return result;
225}
226
cc696296 227int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
a3fe382e 228{
229446df
RS
229 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
230
2234212c 231 if (arg1 != NULL) {
7e1b7485 232 *pass1 = app_get_pass(arg1, same);
2234212c 233 if (*pass1 == NULL)
0f113f3e 234 return 0;
2234212c 235 } else if (pass1 != NULL) {
0f113f3e 236 *pass1 = NULL;
2234212c
PY
237 }
238 if (arg2 != NULL) {
7e1b7485 239 *pass2 = app_get_pass(arg2, same ? 2 : 0);
2234212c 240 if (*pass2 == NULL)
0f113f3e 241 return 0;
2234212c 242 } else if (pass2 != NULL) {
0f113f3e 243 *pass2 = NULL;
2234212c 244 }
0f113f3e 245 return 1;
a3fe382e
DSH
246}
247
cc696296 248static char *app_get_pass(const char *arg, int keepbio)
a3fe382e 249{
0f113f3e 250 static BIO *pwdbio = NULL;
229446df 251 char *tmp, tpass[APP_PASS_LEN];
0f113f3e 252 int i;
86885c28 253
62ca1565 254 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
2ff286c2
DDO
255 if (CHECK_AND_SKIP_PREFIX(arg, "pass:"))
256 return OPENSSL_strdup(arg);
257 if (CHECK_AND_SKIP_PREFIX(arg, "env:")) {
258 tmp = getenv(arg);
2234212c 259 if (tmp == NULL) {
2ff286c2 260 BIO_printf(bio_err, "No environment variable %s\n", arg);
0f113f3e
MC
261 return NULL;
262 }
7644a9ae 263 return OPENSSL_strdup(tmp);
0f113f3e 264 }
2234212c 265 if (!keepbio || pwdbio == NULL) {
2ff286c2
DDO
266 if (CHECK_AND_SKIP_PREFIX(arg, "file:")) {
267 pwdbio = BIO_new_file(arg, "r");
2234212c 268 if (pwdbio == NULL) {
2ff286c2 269 BIO_printf(bio_err, "Can't open file %s\n", arg);
0f113f3e
MC
270 return NULL;
271 }
eff7cb41 272#if !defined(_WIN32)
0f113f3e
MC
273 /*
274 * Under _WIN32, which covers even Win64 and CE, file
275 * descriptors referenced by BIO_s_fd are not inherited
276 * by child process and therefore below is not an option.
277 * It could have been an option if bss_fd.c was operating
278 * on real Windows descriptors, such as those obtained
279 * with CreateFile.
280 */
2ff286c2 281 } else if (CHECK_AND_SKIP_PREFIX(arg, "fd:")) {
0f113f3e 282 BIO *btmp;
8cdb993d 283
2ff286c2 284 i = atoi(arg);
0f113f3e
MC
285 if (i >= 0)
286 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
fa17f5c9 287 if ((i < 0) || pwdbio == NULL) {
2ff286c2 288 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg);
0f113f3e
MC
289 return NULL;
290 }
291 /*
292 * Can't do BIO_gets on an fd BIO so add a buffering BIO
293 */
294 btmp = BIO_new(BIO_f_buffer());
fa17f5c9 295 if (btmp == NULL) {
296 BIO_free_all(pwdbio);
297 pwdbio = NULL;
298 BIO_printf(bio_err, "Out of memory\n");
299 return NULL;
300 }
0f113f3e
MC
301 pwdbio = BIO_push(btmp, pwdbio);
302#endif
86885c28 303 } else if (strcmp(arg, "stdin") == 0) {
a60994df 304 pwdbio = dup_bio_in(FORMAT_TEXT);
12a765a5 305 if (pwdbio == NULL) {
7e1b7485 306 BIO_printf(bio_err, "Can't open BIO for stdin\n");
0f113f3e
MC
307 return NULL;
308 }
309 } else {
62ca1565
DO
310 /* argument syntax error; do not reveal too much about arg */
311 tmp = strchr(arg, ':');
312 if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
313 BIO_printf(bio_err,
314 "Invalid password argument, missing ':' within the first %d chars\n",
315 PASS_SOURCE_SIZE_MAX + 1);
316 else
317 BIO_printf(bio_err,
318 "Invalid password argument, starting with \"%.*s\"\n",
319 (int)(tmp - arg + 1), arg);
0f113f3e
MC
320 return NULL;
321 }
322 }
323 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
324 if (keepbio != 1) {
325 BIO_free_all(pwdbio);
326 pwdbio = NULL;
327 }
328 if (i <= 0) {
7e1b7485 329 BIO_printf(bio_err, "Error reading password from BIO\n");
0f113f3e
MC
330 return NULL;
331 }
332 tmp = strchr(tpass, '\n');
2234212c 333 if (tmp != NULL)
0f113f3e 334 *tmp = 0;
7644a9ae 335 return OPENSSL_strdup(tpass);
a3fe382e 336}
90ae4673 337
bfa470a4 338CONF *app_load_config_bio(BIO *in, const char *filename)
cc01d217
RS
339{
340 long errorline = -1;
341 CONF *conf;
342 int i;
cc01d217 343
a1fb5eb9 344 conf = NCONF_new_ex(app_get0_libctx(), NULL);
cc01d217 345 i = NCONF_load_bio(conf, in, &errorline);
cc01d217
RS
346 if (i > 0)
347 return conf;
348
bfa470a4
RL
349 if (errorline <= 0) {
350 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
351 } else {
352 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
353 errorline);
354 }
355 if (filename != NULL)
356 BIO_printf(bio_err, "config file \"%s\"\n", filename);
cc01d217 357 else
bfa470a4
RL
358 BIO_printf(bio_err, "config input");
359
cc01d217
RS
360 NCONF_free(conf);
361 return NULL;
362}
2234212c 363
15795943 364CONF *app_load_config_verbose(const char *filename, int verbose)
296f54ee 365{
15795943
DDO
366 if (verbose) {
367 if (*filename == '\0')
368 BIO_printf(bio_err, "No configuration used\n");
369 else
370 BIO_printf(bio_err, "Using configuration from %s\n", filename);
371 }
372 return app_load_config_internal(filename, 0);
296f54ee 373}
2234212c 374
15795943 375CONF *app_load_config_internal(const char *filename, int quiet)
296f54ee 376{
18d9c9bf 377 BIO *in;
296f54ee
RL
378 CONF *conf;
379
18d9c9bf
TM
380 if (filename == NULL || *filename != '\0') {
381 if ((in = bio_open_default_(filename, 'r', FORMAT_TEXT, quiet)) == NULL)
382 return NULL;
383 conf = app_load_config_bio(in, filename);
384 BIO_free(in);
385 } else {
386 /* Return empty config if filename is empty string. */
a1fb5eb9 387 conf = NCONF_new_ex(app_get0_libctx(), NULL);
18d9c9bf 388 }
296f54ee
RL
389 return conf;
390}
391
392int app_load_modules(const CONF *config)
393{
394 CONF *to_free = NULL;
395
396 if (config == NULL)
dccd20d1 397 config = to_free = app_load_config_quiet(default_config_file);
296f54ee 398 if (config == NULL)
dccd20d1 399 return 1;
296f54ee
RL
400
401 if (CONF_modules_load(config, NULL, 0) <= 0) {
402 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
403 ERR_print_errors(bio_err);
404 NCONF_free(to_free);
405 return 0;
406 }
407 NCONF_free(to_free);
408 return 1;
409}
cc01d217 410
7e1b7485 411int add_oid_section(CONF *conf)
0f113f3e
MC
412{
413 char *p;
414 STACK_OF(CONF_VALUE) *sktmp;
415 CONF_VALUE *cnf;
416 int i;
75ebbd9a
RS
417
418 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
0f113f3e
MC
419 ERR_clear_error();
420 return 1;
421 }
75ebbd9a 422 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
7e1b7485 423 BIO_printf(bio_err, "problem loading oid section %s\n", p);
0f113f3e
MC
424 return 0;
425 }
426 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
427 cnf = sk_CONF_VALUE_value(sktmp, i);
428 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
7e1b7485 429 BIO_printf(bio_err, "problem creating object %s=%s\n",
0f113f3e
MC
430 cnf->name, cnf->value);
431 return 0;
432 }
433 }
434 return 1;
431b0cce
RL
435}
436
ae89578b
SL
437CONF *app_load_config_modules(const char *configfile)
438{
439 CONF *conf = NULL;
440
441 if (configfile != NULL) {
15795943 442 if ((conf = app_load_config_verbose(configfile, 1)) == NULL)
ae89578b
SL
443 return NULL;
444 if (configfile != default_config_file && !app_load_modules(conf)) {
445 NCONF_free(conf);
446 conf = NULL;
447 }
448 }
449 return conf;
450}
451
2ff286c2
DDO
452#define IS_HTTP(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTP_PREFIX))
453#define IS_HTTPS(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTPS_PREFIX))
9498dac4 454
d382e796 455X509 *load_cert_pass(const char *uri, int format, int maybe_stdin,
6d382c74 456 const char *pass, const char *desc)
0f113f3e 457{
6d382c74 458 X509 *cert = NULL;
0f113f3e 459
6d382c74
DDO
460 if (desc == NULL)
461 desc = "certificate";
6e249947 462 if (IS_HTTPS(uri)) {
9498dac4 463 BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
6e249947 464 } else if (IS_HTTP(uri)) {
9498dac4 465 cert = X509_load_http(uri, NULL, NULL, 0 /* timeout */);
6e249947
DDO
466 if (cert == NULL) {
467 ERR_print_errors(bio_err);
468 BIO_printf(bio_err, "Unable to load %s from %s\n", desc, uri);
469 }
470 } else {
d382e796 471 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
9498dac4 472 NULL, NULL, NULL, &cert, NULL, NULL, NULL);
0f113f3e 473 }
6d382c74 474 return cert;
0f113f3e 475}
90ae4673 476
d382e796
TM
477X509_CRL *load_crl(const char *uri, int format, int maybe_stdin,
478 const char *desc)
6d382c74
DDO
479{
480 X509_CRL *crl = NULL;
9d5aca65 481
6d382c74
DDO
482 if (desc == NULL)
483 desc = "CRL";
6e249947 484 if (IS_HTTPS(uri)) {
9498dac4 485 BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
6e249947 486 } else if (IS_HTTP(uri)) {
9498dac4 487 crl = X509_CRL_load_http(uri, NULL, NULL, 0 /* timeout */);
6e249947
DDO
488 if (crl == NULL) {
489 ERR_print_errors(bio_err);
490 BIO_printf(bio_err, "Unable to load %s from %s\n", desc, uri);
491 }
492 } else {
d382e796 493 (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
9498dac4 494 NULL, NULL, NULL, NULL, NULL, &crl, NULL);
0f113f3e 495 }
6d382c74 496 return crl;
9d5aca65
DO
497}
498
499X509_REQ *load_csr(const char *file, int format, const char *desc)
500{
501 X509_REQ *req = NULL;
502 BIO *in;
503
d382e796
TM
504 if (format == FORMAT_UNDEF)
505 format = FORMAT_PEM;
6d382c74
DDO
506 if (desc == NULL)
507 desc = "CSR";
9d5aca65
DO
508 in = bio_open_default(file, 'r', format);
509 if (in == NULL)
510 goto end;
511
512 if (format == FORMAT_ASN1)
513 req = d2i_X509_REQ_bio(in, NULL);
514 else if (format == FORMAT_PEM)
515 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
3ee4e8ce 516 else
51c833ac 517 print_format_error(format, OPT_FMT_PEMDER);
fdb78f3d 518
0f113f3e 519 end:
6d382c74 520 if (req == NULL) {
9d5aca65 521 ERR_print_errors(bio_err);
6e249947 522 BIO_printf(bio_err, "Unable to load %s\n", desc);
9d5aca65 523 }
0f113f3e 524 BIO_free(in);
9d5aca65 525 return req;
0f113f3e 526}
fdb78f3d 527
6d382c74
DDO
528void cleanse(char *str)
529{
530 if (str != NULL)
531 OPENSSL_cleanse(str, strlen(str));
532}
533
534void clear_free(char *str)
535{
536 if (str != NULL)
537 OPENSSL_clear_free(str, strlen(str));
538}
539
540EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
9d5aca65 541 const char *pass, ENGINE *e, const char *desc)
0f113f3e 542{
0f113f3e 543 EVP_PKEY *pkey = NULL;
f91d003a 544 char *allocated_uri = NULL;
0f113f3e 545
6d382c74
DDO
546 if (desc == NULL)
547 desc = "private key";
0f113f3e 548
0f113f3e 549 if (format == FORMAT_ENGINE) {
f91d003a 550 uri = allocated_uri = make_engine_uri(e, uri, desc);
0f113f3e 551 }
d382e796 552 (void)load_key_certs_crls(uri, format, may_stdin, pass, desc,
f91d003a 553 &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
3ee4e8ce 554
f91d003a 555 OPENSSL_free(allocated_uri);
26a7d938 556 return pkey;
0f113f3e 557}
90ae4673 558
6d382c74 559EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
9d5aca65 560 const char *pass, ENGINE *e, const char *desc)
0f113f3e 561{
0f113f3e 562 EVP_PKEY *pkey = NULL;
f91d003a 563 char *allocated_uri = NULL;
0f113f3e 564
6d382c74
DDO
565 if (desc == NULL)
566 desc = "public key";
0f113f3e 567
0f113f3e 568 if (format == FORMAT_ENGINE) {
f91d003a 569 uri = allocated_uri = make_engine_uri(e, uri, desc);
2234212c 570 }
d382e796 571 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
f91d003a 572 NULL, &pkey, NULL, NULL, NULL, NULL, NULL);
2c90e80d 573
f91d003a 574 OPENSSL_free(allocated_uri);
26a7d938 575 return pkey;
0f113f3e 576}
bd08a2bd 577
ef044913 578EVP_PKEY *load_keyparams_suppress(const char *uri, int format, int maybe_stdin,
8cdb993d
DDO
579 const char *keytype, const char *desc,
580 int suppress_decode_errors)
b78c777e
RL
581{
582 EVP_PKEY *params = NULL;
6e249947 583 BIO *bio_bak = bio_err;
b78c777e
RL
584
585 if (desc == NULL)
586 desc = "key parameters";
6e249947
DDO
587 if (suppress_decode_errors)
588 bio_err = NULL;
589 (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
590 NULL, NULL, &params, NULL, NULL, NULL, NULL);
8b0ec099 591 if (params != NULL && keytype != NULL && !EVP_PKEY_is_a(params, keytype)) {
6e249947
DDO
592 ERR_print_errors(bio_err);
593 BIO_printf(bio_err,
594 "Unable to load %s from %s (unexpected parameters type)\n",
595 desc, uri);
8b0ec099
MC
596 EVP_PKEY_free(params);
597 params = NULL;
b78c777e 598 }
6e249947 599 bio_err = bio_bak;
b78c777e
RL
600 return params;
601}
602
ef044913
SL
603EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin,
604 const char *keytype, const char *desc)
605{
606 return load_keyparams_suppress(uri, format, maybe_stdin, keytype, desc, 0);
607}
608
e306f83c
RL
609void app_bail_out(char *fmt, ...)
610{
611 va_list args;
612
613 va_start(args, fmt);
614 BIO_vprintf(bio_err, fmt, args);
615 va_end(args);
616 ERR_print_errors(bio_err);
a7e4ca5b 617 exit(EXIT_FAILURE);
e306f83c
RL
618}
619
b1c908f4 620void *app_malloc(size_t sz, const char *what)
68dc6824
RS
621{
622 void *vp = OPENSSL_malloc(sz);
623
e306f83c 624 if (vp == NULL)
b1c908f4 625 app_bail_out("%s: Could not allocate %zu bytes for %s\n",
e306f83c 626 opt_getprog(), sz, what);
68dc6824
RS
627 return vp;
628}
629
f62846b7
DDO
630char *next_item(char *opt) /* in list separated by comma and/or space */
631{
632 /* advance to separator (comma or whitespace), if any */
db89d8f0 633 while (*opt != ',' && !isspace(*opt) && *opt != '\0')
f62846b7 634 opt++;
f62846b7
DDO
635 if (*opt != '\0') {
636 /* terminate current item */
637 *opt++ = '\0';
638 /* skip over any whitespace after separator */
639 while (isspace(*opt))
640 opt++;
641 }
642 return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
643}
644
645static void warn_cert_msg(const char *uri, X509 *cert, const char *msg)
646{
647 char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
648
49f07be4 649 BIO_printf(bio_err, "Warning: certificate from '%s' with subject '%s' %s\n",
f62846b7
DDO
650 uri, subj, msg);
651 OPENSSL_free(subj);
652}
653
654static void warn_cert(const char *uri, X509 *cert, int warn_EE,
655 X509_VERIFY_PARAM *vpm)
656{
657 uint32_t ex_flags = X509_get_extension_flags(cert);
658 int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
659 X509_get0_notAfter(cert));
660
661 if (res != 0)
662 warn_cert_msg(uri, cert, res > 0 ? "has expired" : "not yet valid");
663 if (warn_EE && (ex_flags & EXFLAG_V1) == 0 && (ex_flags & EXFLAG_CA) == 0)
664 warn_cert_msg(uri, cert, "is not a CA cert");
665}
666
667static void warn_certs(const char *uri, STACK_OF(X509) *certs, int warn_EE,
668 X509_VERIFY_PARAM *vpm)
669{
670 int i;
671
672 for (i = 0; i < sk_X509_num(certs); i++)
673 warn_cert(uri, sk_X509_value(certs, i), warn_EE, vpm);
674}
675
676int load_cert_certs(const char *uri,
677 X509 **pcert, STACK_OF(X509) **pcerts,
678 int exclude_http, const char *pass, const char *desc,
679 X509_VERIFY_PARAM *vpm)
680{
681 int ret = 0;
682 char *pass_string;
683
6e249947
DDO
684 if (desc == NULL)
685 desc = pcerts == NULL ? "certificate" : "certificates";
747adb6a
DDO
686 if (exclude_http && (HAS_CASE_PREFIX(uri, "http://")
687 || HAS_CASE_PREFIX(uri, "https://"))) {
f62846b7
DDO
688 BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
689 return ret;
690 }
691 pass_string = get_passwd(pass, desc);
d382e796 692 ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass_string, desc,
6e249947 693 NULL, NULL, NULL, pcert, pcerts, NULL, NULL);
f62846b7
DDO
694 clear_free(pass_string);
695
696 if (ret) {
697 if (pcert != NULL)
698 warn_cert(uri, *pcert, 0, vpm);
8c870f6b
P
699 if (pcerts != NULL)
700 warn_certs(uri, *pcerts, 1, vpm);
f62846b7 701 } else {
8c870f6b
P
702 if (pcerts != NULL) {
703 OSSL_STACK_OF_X509_free(*pcerts);
704 *pcerts = NULL;
705 }
f62846b7
DDO
706 }
707 return ret;
708}
709
710STACK_OF(X509) *load_certs_multifile(char *files, const char *pass,
711 const char *desc, X509_VERIFY_PARAM *vpm)
712{
713 STACK_OF(X509) *certs = NULL;
714 STACK_OF(X509) *result = sk_X509_new_null();
715
716 if (files == NULL)
717 goto err;
718 if (result == NULL)
719 goto oom;
720
721 while (files != NULL) {
722 char *next = next_item(files);
723
724 if (!load_cert_certs(files, NULL, &certs, 0, pass, desc, vpm))
725 goto err;
726 if (!X509_add_certs(result, certs,
727 X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
728 goto oom;
79b2a2f2 729 OSSL_STACK_OF_X509_free(certs);
f62846b7
DDO
730 certs = NULL;
731 files = next;
732 }
733 return result;
734
735 oom:
736 BIO_printf(bio_err, "out of memory\n");
737 err:
79b2a2f2
DDO
738 OSSL_STACK_OF_X509_free(certs);
739 OSSL_STACK_OF_X509_free(result);
f62846b7
DDO
740 return NULL;
741}
742
743static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
744 const STACK_OF(X509) *certs /* may NULL */)
745{
746 int i;
747
748 if (store == NULL)
749 store = X509_STORE_new();
750 if (store == NULL)
751 return NULL;
752 for (i = 0; i < sk_X509_num(certs); i++) {
753 if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
754 X509_STORE_free(store);
755 return NULL;
756 }
757 }
758 return store;
759}
760
761/*
762 * Create cert store structure with certificates read from given file(s).
763 * Returns pointer to created X509_STORE on success, NULL on error.
764 */
765X509_STORE *load_certstore(char *input, const char *pass, const char *desc,
766 X509_VERIFY_PARAM *vpm)
767{
768 X509_STORE *store = NULL;
769 STACK_OF(X509) *certs = NULL;
770
771 while (input != NULL) {
772 char *next = next_item(input);
773 int ok;
774
775 if (!load_cert_certs(input, NULL, &certs, 1, pass, desc, vpm)) {
776 X509_STORE_free(store);
777 return NULL;
778 }
779 ok = (store = sk_X509_to_store(store, certs)) != NULL;
79b2a2f2 780 OSSL_STACK_OF_X509_free(certs);
f62846b7
DDO
781 certs = NULL;
782 if (!ok)
783 return NULL;
784 input = next;
785 }
786 return store;
787}
788
0996dc54 789/*
6b4a77f5 790 * Initialize or extend, if *certs != NULL, a certificate stack.
c4adc5ba 791 * The caller is responsible for freeing *certs if its value is left not NULL.
0996dc54 792 */
ea51096e 793int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs,
a773b52a 794 const char *pass, const char *desc)
0f113f3e 795{
6e249947
DDO
796 int ret, was_NULL = *certs == NULL;
797
798 if (desc == NULL)
799 desc = "certificates";
800 ret = load_key_certs_crls(uri, FORMAT_UNDEF, maybe_stdin, pass, desc,
801 NULL, NULL, NULL, NULL, certs, NULL, NULL);
c4adc5ba
DDO
802
803 if (!ret && was_NULL) {
79b2a2f2 804 OSSL_STACK_OF_X509_free(*certs);
c4adc5ba
DDO
805 *certs = NULL;
806 }
807 return ret;
0f113f3e 808}
245d2ee3 809
0996dc54 810/*
6b4a77f5 811 * Initialize or extend, if *crls != NULL, a certificate stack.
c4adc5ba 812 * The caller is responsible for freeing *crls if its value is left not NULL.
0996dc54 813 */
b3c5aadf 814int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
a773b52a 815 const char *pass, const char *desc)
0f113f3e 816{
6e249947
DDO
817 int ret, was_NULL = *crls == NULL;
818
819 if (desc == NULL)
820 desc = "CRLs";
821 ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass, desc,
822 NULL, NULL, NULL, NULL, NULL, NULL, crls);
c4adc5ba
DDO
823
824 if (!ret && was_NULL) {
825 sk_X509_CRL_pop_free(*crls, X509_CRL_free);
826 *crls = NULL;
827 }
828 return ret;
0f113f3e
MC
829}
830
d382e796
TM
831static const char *format2string(int format)
832{
1287dabd 833 switch (format) {
d382e796
TM
834 case FORMAT_PEM:
835 return "PEM";
836 case FORMAT_ASN1:
837 return "DER";
838 }
839 return NULL;
840}
841
6c3d101a 842/* Set type expectation, but clear it if objects of different types expected. */
8cdb993d
DDO
843#define SET_EXPECT(val) \
844 (expect = expect < 0 ? (val) : (expect == (val) ? (val) : 0))
845#define SET_EXPECT1(pvar, val) \
846 if ((pvar) != NULL) { \
847 *(pvar) = NULL; \
848 SET_EXPECT(val); \
849 }
850#define FAIL_NAME \
851 (ppkey != NULL ? "key etc." : ppubkey != NULL ? "public key etc." : \
852 pparams != NULL ? "params etc." : \
853 pcert != NULL ? "cert etc." : pcerts != NULL ? "certs etc." : \
854 pcrl != NULL ? "CRL etc." : pcrls != NULL ? "CRLs etc." : NULL)
6d382c74
DDO
855/*
856 * Load those types of credentials for which the result pointer is not NULL.
857 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
b3c5aadf
DDO
858 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
859 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
860 * If pcerts is non-NULL then all available certificates are appended to *pcerts
861 * except any certificate assigned to *pcert.
862 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
863 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
864 * except any CRL assigned to *pcrl.
865 * In any case (also on error) the caller is responsible for freeing all members
866 * of *pcerts and *pcrls (as far as they are not NULL).
6d382c74 867 */
6e249947 868int load_key_certs_crls(const char *uri, int format, int maybe_stdin,
8cdb993d
DDO
869 const char *pass, const char *desc, EVP_PKEY **ppkey,
870 EVP_PKEY **ppubkey, EVP_PKEY **pparams,
6e249947
DDO
871 X509 **pcert, STACK_OF(X509) **pcerts,
872 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
6d382c74
DDO
873{
874 PW_CB_DATA uidata;
875 OSSL_STORE_CTX *ctx = NULL;
b4250010 876 OSSL_LIB_CTX *libctx = app_get0_libctx();
6725682d 877 const char *propq = app_get0_propq();
8cdb993d
DDO
878 int ncerts = 0, ncrls = 0, expect = -1;
879 const char *failed = FAIL_NAME;
d382e796
TM
880 const char *input_type;
881 OSSL_PARAM itp[2];
882 const OSSL_PARAM *params = NULL;
6d382c74 883
8cdb993d
DDO
884 if (failed == NULL) {
885 BIO_printf(bio_err, "Internal error: nothing to load from %s\n",
886 uri != NULL ? uri : "<stdin>");
887 return 0;
f91d003a 888 }
8cdb993d
DDO
889 ERR_set_mark();
890
891 SET_EXPECT1(ppkey, OSSL_STORE_INFO_PKEY);
892 SET_EXPECT1(ppubkey, OSSL_STORE_INFO_PUBKEY);
893 SET_EXPECT1(pparams, OSSL_STORE_INFO_PARAMS);
894 SET_EXPECT1(pcert, OSSL_STORE_INFO_CERT);
3a2171f6
MC
895 if (pcerts != NULL) {
896 if (*pcerts == NULL && (*pcerts = sk_X509_new_null()) == NULL) {
897 BIO_printf(bio_err, "Out of memory loading");
898 goto end;
899 }
8cdb993d 900 SET_EXPECT(OSSL_STORE_INFO_CERT);
f91d003a 901 }
8cdb993d 902 SET_EXPECT1(pcrl, OSSL_STORE_INFO_CRL);
3a2171f6
MC
903 if (pcrls != NULL) {
904 if (*pcrls == NULL && (*pcrls = sk_X509_CRL_new_null()) == NULL) {
905 BIO_printf(bio_err, "Out of memory loading");
906 goto end;
907 }
8cdb993d 908 SET_EXPECT(OSSL_STORE_INFO_CRL);
b3c5aadf 909 }
6d382c74 910
6d382c74
DDO
911 uidata.password = pass;
912 uidata.prompt_info = uri;
913
d382e796 914 if ((input_type = format2string(format)) != NULL) {
8cdb993d
DDO
915 itp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE,
916 (char *)input_type, 0);
917 itp[1] = OSSL_PARAM_construct_end();
918 params = itp;
d382e796
TM
919 }
920
6d382c74
DDO
921 if (uri == NULL) {
922 BIO *bio;
923
924 if (!maybe_stdin) {
50eb2a50 925 BIO_printf(bio_err, "No filename or uri specified for loading");
6d382c74
DDO
926 goto end;
927 }
50eb2a50 928 uri = "<stdin>";
6d382c74
DDO
929 unbuffer(stdin);
930 bio = BIO_new_fp(stdin, 0);
857c223b 931 if (bio != NULL) {
6725682d 932 ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
d382e796
TM
933 get_ui_method(), &uidata, params,
934 NULL, NULL);
857c223b
SL
935 BIO_free(bio);
936 }
6d382c74 937 } else {
d8652be0 938 ctx = OSSL_STORE_open_ex(uri, libctx, propq, get_ui_method(), &uidata,
d382e796 939 params, NULL, NULL);
6d382c74
DDO
940 }
941 if (ctx == NULL) {
50eb2a50 942 BIO_printf(bio_err, "Could not open file or uri for loading");
6d382c74
DDO
943 goto end;
944 }
6c3d101a 945 if (expect > 0 && !OSSL_STORE_expect(ctx, expect))
f91d003a
RL
946 goto end;
947
87495d56 948 failed = NULL;
8cdb993d
DDO
949 while ((ppkey != NULL || ppubkey != NULL || pparams != NULL
950 || pcert != NULL || pcerts != NULL || pcrl != NULL || pcrls != NULL)
951 && !OSSL_STORE_eof(ctx)) {
6d382c74 952 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
50eb2a50 953 int type, ok = 1;
6d382c74 954
3a2171f6
MC
955 /*
956 * This can happen (for example) if we attempt to load a file with
957 * multiple different types of things in it - but the thing we just
958 * tried to load wasn't one of the ones we wanted, e.g. if we're trying
959 * to load a certificate but the file has both the private key and the
960 * certificate in it. We just retry until eof.
961 */
962 if (info == NULL) {
3a2171f6
MC
963 continue;
964 }
965
50eb2a50 966 type = OSSL_STORE_INFO_get_type(info);
6d382c74
DDO
967 switch (type) {
968 case OSSL_STORE_INFO_PKEY:
8cdb993d 969 if (ppkey != NULL) {
b3c5aadf 970 ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
8cdb993d
DDO
971 if (ok)
972 ppkey = NULL;
973 break;
d8a809db 974 }
2274d22d
RL
975 /*
976 * An EVP_PKEY with private parts also holds the public parts,
977 * so if the caller asked for a public key, and we got a private
978 * key, we can still pass it back.
979 */
8cdb993d 980 /* fall thru */
2274d22d 981 case OSSL_STORE_INFO_PUBKEY:
8cdb993d
DDO
982 if (ppubkey != NULL) {
983 ok = (*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL;
984 if (ok)
985 ppubkey = NULL;
d8a809db 986 }
6d382c74 987 break;
b78c777e 988 case OSSL_STORE_INFO_PARAMS:
8cdb993d
DDO
989 if (pparams != NULL) {
990 ok = (*pparams = OSSL_STORE_INFO_get1_PARAMS(info)) != NULL;
991 if (ok)
992 pparams = NULL;
d8a809db 993 }
b78c777e 994 break;
6d382c74 995 case OSSL_STORE_INFO_CERT:
8cdb993d 996 if (pcert != NULL) {
b3c5aadf 997 ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
8cdb993d
DDO
998 if (ok)
999 pcert = NULL;
1000 } else if (pcerts != NULL) {
b3c5aadf
DDO
1001 ok = X509_add_cert(*pcerts,
1002 OSSL_STORE_INFO_get1_CERT(info),
1003 X509_ADD_FLAG_DEFAULT);
8cdb993d 1004 }
b3c5aadf 1005 ncerts += ok;
6d382c74
DDO
1006 break;
1007 case OSSL_STORE_INFO_CRL:
8cdb993d 1008 if (pcrl != NULL) {
b3c5aadf 1009 ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
8cdb993d
DDO
1010 if (ok)
1011 pcrl = NULL;
1012 } else if (pcrls != NULL) {
b3c5aadf 1013 ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info));
8cdb993d 1014 }
b3c5aadf 1015 ncrls += ok;
6d382c74
DDO
1016 break;
1017 default:
1018 /* skip any other type */
1019 break;
1020 }
1021 OSSL_STORE_INFO_free(info);
b3c5aadf 1022 if (!ok) {
8cdb993d 1023 failed = OSSL_STORE_INFO_type_string(type);
50eb2a50 1024 BIO_printf(bio_err, "Error reading");
6d382c74
DDO
1025 break;
1026 }
1027 }
1028
1029 end:
1030 OSSL_STORE_close(ctx);
8cdb993d
DDO
1031 if (ncerts > 0)
1032 pcerts = NULL;
1033 if (ncrls > 0)
1034 pcrls = NULL;
87495d56 1035 if (failed == NULL) {
8cdb993d 1036 failed = FAIL_NAME;
6e249947
DDO
1037 if (failed != NULL)
1038 BIO_printf(bio_err, "Could not read");
b3c5aadf 1039 }
6e249947
DDO
1040 if (failed != NULL) {
1041 unsigned long err = ERR_peek_last_error();
1042
50eb2a50
DDO
1043 if (desc != NULL && strstr(desc, failed) != NULL) {
1044 BIO_printf(bio_err, " %s", desc);
1045 } else {
1046 BIO_printf(bio_err, " %s", failed);
1047 if (desc != NULL)
1048 BIO_printf(bio_err, " of %s", desc);
1049 }
1050 if (uri != NULL)
1051 BIO_printf(bio_err, " from %s", uri);
6e249947
DDO
1052 if (ERR_SYSTEM_ERROR(err)) {
1053 /* provide more readable diagnostic output */
1054 BIO_printf(bio_err, ": %s", strerror(ERR_GET_REASON(err)));
1055 ERR_pop_to_mark();
1056 ERR_set_mark();
1057 }
50eb2a50 1058 BIO_printf(bio_err, "\n");
87495d56 1059 ERR_print_errors(bio_err);
50eb2a50 1060 }
6e249947
DDO
1061 if (bio_err == NULL || failed == NULL)
1062 /* clear any suppressed or spurious errors */
1063 ERR_pop_to_mark();
1064 else
1065 ERR_clear_last_mark();
b3c5aadf 1066 return failed == NULL;
6d382c74
DDO
1067}
1068
8cdb993d
DDO
1069#define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
1070#define X509V3_EXT_DEFAULT 0 /* Return error for unknown exts */
1071#define X509V3_EXT_ERROR_UNKNOWN (1L << 16) /* Print error for unknown exts */
1072#define X509V3_EXT_PARSE_UNKNOWN (2L << 16) /* ASN1 parse unknown extensions */
1073#define X509V3_EXT_DUMP_UNKNOWN (3L << 16) /* BIO_dump unknown extensions */
8ca533e3 1074
535d79da 1075#define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
8cdb993d 1076 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
535d79da 1077
8ca533e3
DSH
1078int set_cert_ex(unsigned long *flags, const char *arg)
1079{
0f113f3e
MC
1080 static const NAME_EX_TBL cert_tbl[] = {
1081 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
1082 {"ca_default", X509_FLAG_CA, 0xffffffffl},
1083 {"no_header", X509_FLAG_NO_HEADER, 0},
1084 {"no_version", X509_FLAG_NO_VERSION, 0},
1085 {"no_serial", X509_FLAG_NO_SERIAL, 0},
1086 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
1087 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
1088 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
1089 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1090 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1091 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1092 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1093 {"no_aux", X509_FLAG_NO_AUX, 0},
1094 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1095 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1096 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1097 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1098 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1099 {NULL, 0, 0}
1100 };
1101 return set_multi_opts(flags, arg, cert_tbl);
8ca533e3 1102}
a657546f
DSH
1103
1104int set_name_ex(unsigned long *flags, const char *arg)
1105{
0f113f3e
MC
1106 static const NAME_EX_TBL ex_tbl[] = {
1107 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
bc776510 1108 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
0f113f3e
MC
1109 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1110 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1111 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1112 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1113 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1114 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1115 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1116 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1117 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1118 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1119 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1120 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1121 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1122 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1123 {"dn_rev", XN_FLAG_DN_REV, 0},
1124 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1125 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1126 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1127 {"align", XN_FLAG_FN_ALIGN, 0},
1128 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1129 {"space_eq", XN_FLAG_SPC_EQ, 0},
1130 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1131 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1132 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1133 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1134 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1135 {NULL, 0, 0}
1136 };
03706afa
DSH
1137 if (set_multi_opts(flags, arg, ex_tbl) == 0)
1138 return 0;
3190d1dc
RL
1139 if (*flags != XN_FLAG_COMPAT
1140 && (*flags & XN_FLAG_SEP_MASK) == 0)
03706afa
DSH
1141 *flags |= XN_FLAG_SEP_CPLUS_SPC;
1142 return 1;
535d79da
DSH
1143}
1144
8c5bff22
WE
1145int set_dateopt(unsigned long *dateopt, const char *arg)
1146{
fba140c7 1147 if (OPENSSL_strcasecmp(arg, "rfc_822") == 0)
8c5bff22 1148 *dateopt = ASN1_DTFLGS_RFC822;
fba140c7 1149 else if (OPENSSL_strcasecmp(arg, "iso_8601") == 0)
8c5bff22
WE
1150 *dateopt = ASN1_DTFLGS_ISO8601;
1151 return 0;
1152}
1153
791bd0cd
DSH
1154int set_ext_copy(int *copy_type, const char *arg)
1155{
fba140c7 1156 if (OPENSSL_strcasecmp(arg, "none") == 0)
0f113f3e 1157 *copy_type = EXT_COPY_NONE;
fba140c7 1158 else if (OPENSSL_strcasecmp(arg, "copy") == 0)
0f113f3e 1159 *copy_type = EXT_COPY_ADD;
fba140c7 1160 else if (OPENSSL_strcasecmp(arg, "copyall") == 0)
0f113f3e
MC
1161 *copy_type = EXT_COPY_ALL;
1162 else
1163 return 0;
1164 return 1;
791bd0cd
DSH
1165}
1166
1167int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1168{
03f4e3de
DDO
1169 STACK_OF(X509_EXTENSION) *exts;
1170 int i, ret = 0;
1171
1172 if (x == NULL || req == NULL)
1173 return 0;
1174 if (copy_type == EXT_COPY_NONE)
0f113f3e
MC
1175 return 1;
1176 exts = X509_REQ_get_extensions(req);
1177
1178 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
03f4e3de
DDO
1179 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
1180 ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext);
1181 int idx = X509_get_ext_by_OBJ(x, obj, -1);
1182
1183 /* Does extension exist in target? */
0f113f3e
MC
1184 if (idx != -1) {
1185 /* If normal copy don't override existing extension */
1186 if (copy_type == EXT_COPY_ADD)
1187 continue;
1188 /* Delete all extensions of same type */
1189 do {
05458fdb 1190 X509_EXTENSION_free(X509_delete_ext(x, idx));
0f113f3e
MC
1191 idx = X509_get_ext_by_OBJ(x, obj, -1);
1192 } while (idx != -1);
1193 }
1194 if (!X509_add_ext(x, ext, -1))
1195 goto end;
1196 }
0f113f3e
MC
1197 ret = 1;
1198
1199 end:
0f113f3e 1200 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
0f113f3e
MC
1201 return ret;
1202}
1203
1204static int set_multi_opts(unsigned long *flags, const char *arg,
1205 const NAME_EX_TBL * in_tbl)
1206{
1207 STACK_OF(CONF_VALUE) *vals;
1208 CONF_VALUE *val;
1209 int i, ret = 1;
8cdb993d 1210
0f113f3e
MC
1211 if (!arg)
1212 return 0;
1213 vals = X509V3_parse_list(arg);
1214 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1215 val = sk_CONF_VALUE_value(vals, i);
1216 if (!set_table_opts(flags, val->name, in_tbl))
1217 ret = 0;
1218 }
1219 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1220 return ret;
1221}
1222
1223static int set_table_opts(unsigned long *flags, const char *arg,
1224 const NAME_EX_TBL * in_tbl)
1225{
1226 char c;
1227 const NAME_EX_TBL *ptbl;
0f113f3e 1228
8cdb993d 1229 c = arg[0];
0f113f3e
MC
1230 if (c == '-') {
1231 c = 0;
1232 arg++;
1233 } else if (c == '+') {
1234 c = 1;
1235 arg++;
2234212c 1236 } else {
0f113f3e 1237 c = 1;
2234212c 1238 }
0f113f3e
MC
1239
1240 for (ptbl = in_tbl; ptbl->name; ptbl++) {
fba140c7 1241 if (OPENSSL_strcasecmp(arg, ptbl->name) == 0) {
0f113f3e
MC
1242 *flags &= ~ptbl->mask;
1243 if (c)
1244 *flags |= ptbl->flag;
1245 else
1246 *flags &= ~ptbl->flag;
1247 return 1;
1248 }
1249 }
1250 return 0;
1251}
1252
46a11faf 1253void print_name(BIO *out, const char *title, const X509_NAME *nm)
0f113f3e
MC
1254{
1255 char *buf;
1256 char mline = 0;
1257 int indent = 0;
46a11faf 1258 unsigned long lflags = get_nameopt();
e60e9744 1259
32f7be2a
DDO
1260 if (out == NULL)
1261 return;
46a11faf 1262 if (title != NULL)
0f113f3e
MC
1263 BIO_puts(out, title);
1264 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1265 mline = 1;
1266 indent = 4;
1267 }
1268 if (lflags == XN_FLAG_COMPAT) {
1269 buf = X509_NAME_oneline(nm, 0, 0);
1270 BIO_puts(out, buf);
1271 BIO_puts(out, "\n");
1272 OPENSSL_free(buf);
1273 } else {
1274 if (mline)
1275 BIO_puts(out, "\n");
1276 X509_NAME_print_ex(out, nm, indent, lflags);
1277 BIO_puts(out, "\n");
1278 }
a657546f
DSH
1279}
1280
2ac6115d 1281void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
7e1b7485 1282 int len, unsigned char *buffer)
81f169e9 1283{
7e1b7485 1284 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
2234212c 1285 if (BN_is_zero(in)) {
06deb932 1286 BIO_printf(out, "\n 0x00");
2234212c 1287 } else {
7e1b7485
RS
1288 int i, l;
1289
1290 l = BN_bn2bin(in, buffer);
1291 for (i = 0; i < l; i++) {
06deb932 1292 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
7e1b7485 1293 if (i < l - 1)
06deb932 1294 BIO_printf(out, "0x%02X,", buffer[i]);
7e1b7485
RS
1295 else
1296 BIO_printf(out, "0x%02X", buffer[i]);
1297 }
1298 }
1299 BIO_printf(out, "\n };\n");
1300}
2234212c 1301
8cdb993d 1302void print_array(BIO *out, const char *title, int len, const unsigned char *d)
7e1b7485
RS
1303{
1304 int i;
1305
1306 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1307 for (i = 0; i < len; i++) {
1308 if ((i % 10) == 0)
1309 BIO_printf(out, "\n ");
1310 if (i < len - 1)
1311 BIO_printf(out, "0x%02X, ", d[i]);
1312 else
1313 BIO_printf(out, "0x%02X", d[i]);
1314 }
1315 BIO_printf(out, "\n};\n");
1316}
1317
fd3397fc
RL
1318X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1319 const char *CApath, int noCApath,
1320 const char *CAstore, int noCAstore)
7e1b7485
RS
1321{
1322 X509_STORE *store = X509_STORE_new();
0f113f3e 1323 X509_LOOKUP *lookup;
b4250010 1324 OSSL_LIB_CTX *libctx = app_get0_libctx();
6725682d 1325 const char *propq = app_get0_propq();
7e1b7485 1326
96487cdd 1327 if (store == NULL)
0f113f3e 1328 goto end;
2b6bcb70 1329
e8aa8b6c 1330 if (CAfile != NULL || !noCAfile) {
2b6bcb70
MC
1331 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1332 if (lookup == NULL)
0f113f3e 1333 goto end;
fd3397fc 1334 if (CAfile != NULL) {
d8652be0
MC
1335 if (!X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM,
1336 libctx, propq)) {
2b6bcb70
MC
1337 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1338 goto end;
1339 }
2234212c 1340 } else {
d8652be0
MC
1341 X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT,
1342 libctx, propq);
2234212c 1343 }
2b6bcb70 1344 }
0f113f3e 1345
e8aa8b6c 1346 if (CApath != NULL || !noCApath) {
2b6bcb70
MC
1347 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1348 if (lookup == NULL)
0f113f3e 1349 goto end;
fd3397fc 1350 if (CApath != NULL) {
2b6bcb70
MC
1351 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1352 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1353 goto end;
1354 }
2234212c 1355 } else {
2b6bcb70 1356 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
2234212c 1357 }
2b6bcb70 1358 }
0f113f3e 1359
fd3397fc
RL
1360 if (CAstore != NULL || !noCAstore) {
1361 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1362 if (lookup == NULL)
1363 goto end;
d8652be0 1364 if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) {
fd3397fc
RL
1365 if (CAstore != NULL)
1366 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1367 goto end;
1368 }
1369 }
1370
0f113f3e
MC
1371 ERR_clear_error();
1372 return store;
1373 end:
01c12100 1374 ERR_print_errors(bio_err);
0f113f3e
MC
1375 X509_STORE_free(store);
1376 return NULL;
81f169e9 1377}
531d630b 1378
c869da88 1379static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
0f113f3e
MC
1380{
1381 const char *n;
f85b68cd 1382
0f113f3e
MC
1383 n = a[DB_serial];
1384 while (*n == '0')
1385 n++;
739a1eb1 1386 return OPENSSL_LH_strhash(n);
0f113f3e 1387}
f85b68cd 1388
0f113f3e
MC
1389static int index_serial_cmp(const OPENSSL_CSTRING *a,
1390 const OPENSSL_CSTRING *b)
1391{
1392 const char *aa, *bb;
f85b68cd 1393
0f113f3e
MC
1394 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1395 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
26a7d938 1396 return strcmp(aa, bb);
0f113f3e 1397}
f85b68cd
RL
1398
1399static int index_name_qual(char **a)
0f113f3e
MC
1400{
1401 return (a[0][0] == 'V');
1402}
f85b68cd 1403
c869da88 1404static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
0f113f3e 1405{
739a1eb1 1406 return OPENSSL_LH_strhash(a[DB_name]);
0f113f3e 1407}
f85b68cd 1408
c869da88 1409int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
0f113f3e 1410{
26a7d938 1411 return strcmp(a[DB_name], b[DB_name]);
0f113f3e 1412}
f85b68cd 1413
c869da88
DSH
1414static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1415static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1416static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1417static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
f85b68cd
RL
1418#undef BSIZE
1419#define BSIZE 256
cc696296 1420BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
0f113f3e
MC
1421{
1422 BIO *in = NULL;
1423 BIGNUM *ret = NULL;
68b00c23 1424 char buf[1024];
0f113f3e
MC
1425 ASN1_INTEGER *ai = NULL;
1426
1427 ai = ASN1_INTEGER_new();
1428 if (ai == NULL)
1429 goto err;
1430
7e1b7485
RS
1431 in = BIO_new_file(serialfile, "r");
1432 if (in == NULL) {
0f113f3e
MC
1433 if (!create) {
1434 perror(serialfile);
1435 goto err;
0f113f3e 1436 }
7e1b7485
RS
1437 ERR_clear_error();
1438 ret = BN_new();
1439 if (ret == NULL || !rand_serial(ret, ai))
1440 BIO_printf(bio_err, "Out of memory\n");
0f113f3e
MC
1441 } else {
1442 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
01c12100 1443 BIO_printf(bio_err, "Unable to load number from %s\n",
0f113f3e
MC
1444 serialfile);
1445 goto err;
1446 }
1447 ret = ASN1_INTEGER_to_BN(ai, NULL);
1448 if (ret == NULL) {
01c12100 1449 BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
0f113f3e
MC
1450 goto err;
1451 }
1452 }
1453
1454 if (ret && retai) {
1455 *retai = ai;
1456 ai = NULL;
1457 }
f85b68cd 1458 err:
01c12100 1459 ERR_print_errors(bio_err);
ca3a82c3 1460 BIO_free(in);
2ace7450 1461 ASN1_INTEGER_free(ai);
26a7d938 1462 return ret;
0f113f3e
MC
1463}
1464
8cdb993d
DDO
1465int save_serial(const char *serialfile, const char *suffix,
1466 const BIGNUM *serial, ASN1_INTEGER **retai)
0f113f3e
MC
1467{
1468 char buf[1][BSIZE];
1469 BIO *out = NULL;
1470 int ret = 0;
1471 ASN1_INTEGER *ai = NULL;
1472 int j;
1473
1474 if (suffix == NULL)
1475 j = strlen(serialfile);
1476 else
1477 j = strlen(serialfile) + strlen(suffix) + 1;
1478 if (j >= BSIZE) {
01c12100 1479 BIO_printf(bio_err, "File name too long\n");
0f113f3e
MC
1480 goto err;
1481 }
1482
8cdb993d 1483 if (suffix == NULL) {
7644a9ae 1484 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
8cdb993d 1485 } else {
4c771796 1486#ifndef OPENSSL_SYS_VMS
cbe29648 1487 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
4c771796 1488#else
cbe29648 1489 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
4c771796 1490#endif
0f113f3e 1491 }
7e1b7485 1492 out = BIO_new_file(buf[0], "w");
0f113f3e 1493 if (out == NULL) {
0f113f3e
MC
1494 goto err;
1495 }
0f113f3e
MC
1496
1497 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1498 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1499 goto err;
1500 }
1501 i2a_ASN1_INTEGER(out, ai);
1502 BIO_puts(out, "\n");
1503 ret = 1;
1504 if (retai) {
1505 *retai = ai;
1506 ai = NULL;
1507 }
1508 err:
01c12100
DDO
1509 if (!ret)
1510 ERR_print_errors(bio_err);
ca3a82c3 1511 BIO_free_all(out);
2ace7450 1512 ASN1_INTEGER_free(ai);
26a7d938 1513 return ret;
0f113f3e 1514}
f85b68cd 1515
cc696296
F
1516int rotate_serial(const char *serialfile, const char *new_suffix,
1517 const char *old_suffix)
0f113f3e 1518{
bde136c8 1519 char buf[2][BSIZE];
0f113f3e
MC
1520 int i, j;
1521
1522 i = strlen(serialfile) + strlen(old_suffix);
1523 j = strlen(serialfile) + strlen(new_suffix);
1524 if (i > j)
1525 j = i;
1526 if (j + 1 >= BSIZE) {
01c12100 1527 BIO_printf(bio_err, "File name too long\n");
0f113f3e
MC
1528 goto err;
1529 }
4c771796 1530#ifndef OPENSSL_SYS_VMS
cbe29648
RS
1531 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1532 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
4c771796 1533#else
cbe29648
RS
1534 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1535 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
a1ad253f 1536#endif
0f113f3e 1537 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
4c771796 1538#ifdef ENOTDIR
0f113f3e
MC
1539 && errno != ENOTDIR
1540#endif
1541 ) {
1542 BIO_printf(bio_err,
01c12100 1543 "Unable to rename %s to %s\n", serialfile, buf[1]);
0f113f3e
MC
1544 perror("reason");
1545 goto err;
1546 }
0f113f3e
MC
1547 if (rename(buf[0], serialfile) < 0) {
1548 BIO_printf(bio_err,
01c12100 1549 "Unable to rename %s to %s\n", buf[0], serialfile);
0f113f3e
MC
1550 perror("reason");
1551 rename(buf[1], serialfile);
1552 goto err;
1553 }
1554 return 1;
4c771796 1555 err:
01c12100 1556 ERR_print_errors(bio_err);
0f113f3e
MC
1557 return 0;
1558}
4c771796 1559
64674bcc 1560int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
0f113f3e
MC
1561{
1562 BIGNUM *btmp;
1563 int ret = 0;
23a1d5e9 1564
ffb46830 1565 btmp = b == NULL ? BN_new() : b;
96487cdd 1566 if (btmp == NULL)
0f113f3e
MC
1567 return 0;
1568
ffb46830 1569 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
0f113f3e
MC
1570 goto error;
1571 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1572 goto error;
1573
1574 ret = 1;
1575
1576 error:
1577
23a1d5e9 1578 if (btmp != b)
0f113f3e
MC
1579 BN_free(btmp);
1580
1581 return ret;
1582}
64674bcc 1583
cc696296 1584CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
0f113f3e
MC
1585{
1586 CA_DB *retdb = NULL;
1587 TXT_DB *tmpdb = NULL;
7e1b7485 1588 BIO *in;
0f113f3e 1589 CONF *dbattr_conf = NULL;
cc01d217 1590 char buf[BSIZE];
c7d5ea26
VD
1591#ifndef OPENSSL_NO_POSIX_IO
1592 FILE *dbfp;
1593 struct stat dbst;
1594#endif
0f113f3e 1595
7e1b7485 1596 in = BIO_new_file(dbfile, "r");
01c12100 1597 if (in == NULL)
0f113f3e 1598 goto err;
c7d5ea26
VD
1599
1600#ifndef OPENSSL_NO_POSIX_IO
1601 BIO_get_fp(in, &dbfp);
1602 if (fstat(fileno(dbfp), &dbst) == -1) {
ff988500
RS
1603 ERR_raise_data(ERR_LIB_SYS, errno,
1604 "calling fstat(%s)", dbfile);
c7d5ea26
VD
1605 goto err;
1606 }
1607#endif
1608
0f113f3e
MC
1609 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1610 goto err;
f85b68cd
RL
1611
1612#ifndef OPENSSL_SYS_VMS
cbe29648 1613 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
f85b68cd 1614#else
cbe29648 1615 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
0f113f3e 1616#endif
ac454d8d 1617 dbattr_conf = app_load_config_quiet(buf);
0f113f3e 1618
b4faea50 1619 retdb = app_malloc(sizeof(*retdb), "new DB");
0f113f3e
MC
1620 retdb->db = tmpdb;
1621 tmpdb = NULL;
1622 if (db_attr)
1623 retdb->attributes = *db_attr;
8cdb993d 1624 else
0f113f3e 1625 retdb->attributes.unique_subject = 1;
0f113f3e
MC
1626
1627 if (dbattr_conf) {
1628 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
8cdb993d 1629
0f113f3e 1630 if (p) {
0f113f3e
MC
1631 retdb->attributes.unique_subject = parse_yesno(p, 1);
1632 }
1633 }
f85b68cd 1634
c7d5ea26
VD
1635 retdb->dbfname = OPENSSL_strdup(dbfile);
1636#ifndef OPENSSL_NO_POSIX_IO
1637 retdb->dbst = dbst;
1638#endif
1639
f85b68cd 1640 err:
01c12100 1641 ERR_print_errors(bio_err);
efa7dd64 1642 NCONF_free(dbattr_conf);
895cba19 1643 TXT_DB_free(tmpdb);
ca3a82c3 1644 BIO_free_all(in);
0f113f3e
MC
1645 return retdb;
1646}
f85b68cd 1647
a4107d73
VD
1648/*
1649 * Returns > 0 on success, <= 0 on error
1650 */
f85b68cd 1651int index_index(CA_DB *db)
0f113f3e
MC
1652{
1653 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1654 LHASH_HASH_FN(index_serial),
1655 LHASH_COMP_FN(index_serial))) {
1656 BIO_printf(bio_err,
01c12100 1657 "Error creating serial number index:(%ld,%ld,%ld)\n",
0f113f3e 1658 db->db->error, db->db->arg1, db->db->arg2);
01c12100 1659 goto err;
0f113f3e
MC
1660 }
1661
1662 if (db->attributes.unique_subject
1663 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1664 LHASH_HASH_FN(index_name),
1665 LHASH_COMP_FN(index_name))) {
01c12100 1666 BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
0f113f3e 1667 db->db->error, db->db->arg1, db->db->arg2);
01c12100 1668 goto err;
0f113f3e
MC
1669 }
1670 return 1;
01c12100
DDO
1671 err:
1672 ERR_print_errors(bio_err);
1673 return 0;
0f113f3e 1674}
f85b68cd 1675
7d727231 1676int save_index(const char *dbfile, const char *suffix, CA_DB *db)
0f113f3e
MC
1677{
1678 char buf[3][BSIZE];
7e1b7485 1679 BIO *out;
0f113f3e
MC
1680 int j;
1681
0f113f3e
MC
1682 j = strlen(dbfile) + strlen(suffix);
1683 if (j + 6 >= BSIZE) {
01c12100 1684 BIO_printf(bio_err, "File name too long\n");
0f113f3e
MC
1685 goto err;
1686 }
f85b68cd 1687#ifndef OPENSSL_SYS_VMS
cbe29648
RS
1688 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1689 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1690 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
f85b68cd 1691#else
cbe29648
RS
1692 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1693 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1694 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
63b6fe2b 1695#endif
7e1b7485
RS
1696 out = BIO_new_file(buf[0], "w");
1697 if (out == NULL) {
0f113f3e 1698 perror(dbfile);
01c12100 1699 BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
0f113f3e
MC
1700 goto err;
1701 }
1702 j = TXT_DB_write(out, db->db);
7e1b7485 1703 BIO_free(out);
0f113f3e
MC
1704 if (j <= 0)
1705 goto err;
1706
7e1b7485 1707 out = BIO_new_file(buf[1], "w");
7e1b7485 1708 if (out == NULL) {
0f113f3e 1709 perror(buf[2]);
01c12100 1710 BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
0f113f3e
MC
1711 goto err;
1712 }
1713 BIO_printf(out, "unique_subject = %s\n",
1714 db->attributes.unique_subject ? "yes" : "no");
1715 BIO_free(out);
1716
1717 return 1;
f85b68cd 1718 err:
01c12100 1719 ERR_print_errors(bio_err);
0f113f3e
MC
1720 return 0;
1721}
f85b68cd 1722
0f113f3e
MC
1723int rotate_index(const char *dbfile, const char *new_suffix,
1724 const char *old_suffix)
1725{
1726 char buf[5][BSIZE];
1727 int i, j;
1728
1729 i = strlen(dbfile) + strlen(old_suffix);
1730 j = strlen(dbfile) + strlen(new_suffix);
1731 if (i > j)
1732 j = i;
1733 if (j + 6 >= BSIZE) {
01c12100 1734 BIO_printf(bio_err, "File name too long\n");
0f113f3e
MC
1735 goto err;
1736 }
f85b68cd 1737#ifndef OPENSSL_SYS_VMS
cbe29648
RS
1738 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1739 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1740 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1741 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1742 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
f85b68cd 1743#else
cbe29648
RS
1744 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1745 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1746 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1747 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1748 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
63b6fe2b 1749#endif
0f113f3e 1750 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
a1ad253f 1751#ifdef ENOTDIR
0f113f3e 1752 && errno != ENOTDIR
a1ad253f 1753#endif
0f113f3e 1754 ) {
01c12100 1755 BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
0f113f3e
MC
1756 perror("reason");
1757 goto err;
1758 }
0f113f3e 1759 if (rename(buf[0], dbfile) < 0) {
01c12100 1760 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
0f113f3e
MC
1761 perror("reason");
1762 rename(buf[1], dbfile);
1763 goto err;
1764 }
0f113f3e 1765 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
a1ad253f 1766#ifdef ENOTDIR
0f113f3e
MC
1767 && errno != ENOTDIR
1768#endif
1769 ) {
01c12100 1770 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
0f113f3e
MC
1771 perror("reason");
1772 rename(dbfile, buf[0]);
1773 rename(buf[1], dbfile);
1774 goto err;
1775 }
0f113f3e 1776 if (rename(buf[2], buf[4]) < 0) {
01c12100 1777 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
0f113f3e
MC
1778 perror("reason");
1779 rename(buf[3], buf[4]);
1780 rename(dbfile, buf[0]);
1781 rename(buf[1], dbfile);
1782 goto err;
1783 }
1784 return 1;
f85b68cd 1785 err:
01c12100 1786 ERR_print_errors(bio_err);
0f113f3e
MC
1787 return 0;
1788}
f85b68cd
RL
1789
1790void free_index(CA_DB *db)
0f113f3e
MC
1791{
1792 if (db) {
895cba19 1793 TXT_DB_free(db->db);
c7d5ea26 1794 OPENSSL_free(db->dbfname);
0f113f3e
MC
1795 OPENSSL_free(db);
1796 }
1797}
6d5ffb59 1798
ff990440 1799int parse_yesno(const char *str, int def)
0f113f3e 1800{
0f113f3e
MC
1801 if (str) {
1802 switch (*str) {
1803 case 'f': /* false */
1804 case 'F': /* FALSE */
1805 case 'n': /* no */
1806 case 'N': /* NO */
1807 case '0': /* 0 */
1bb2daea 1808 return 0;
0f113f3e
MC
1809 case 't': /* true */
1810 case 'T': /* TRUE */
1811 case 'y': /* yes */
1812 case 'Y': /* YES */
1813 case '1': /* 1 */
1bb2daea 1814 return 1;
0f113f3e
MC
1815 }
1816 }
1bb2daea 1817 return def;
0f113f3e 1818}
03ddbdd9 1819
6d5ffb59 1820/*
db4c08f0 1821 * name is expected to be in the format /type0=value0/type1=value1/type2=...
5a0991d0
DDO
1822 * where + can be used instead of / to form multi-valued RDNs if canmulti
1823 * and characters may be escaped by \
6d5ffb59 1824 */
57c05c57
DDO
1825X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
1826 const char *desc)
0f113f3e 1827{
db4c08f0
RS
1828 int nextismulti = 0;
1829 char *work;
1830 X509_NAME *n;
0f113f3e 1831
2167640b
EC
1832 if (*cp++ != '/') {
1833 BIO_printf(bio_err,
57c05c57 1834 "%s: %s name is expected to be in the format "
2167640b
EC
1835 "/type0=value0/type1=value1/type2=... where characters may "
1836 "be escaped by \\. This name is not in that format: '%s'\n",
57c05c57 1837 opt_getprog(), desc, --cp);
db4c08f0 1838 return NULL;
2167640b 1839 }
db4c08f0
RS
1840
1841 n = X509_NAME_new();
57c05c57
DDO
1842 if (n == NULL) {
1843 BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
db4c08f0 1844 return NULL;
57c05c57 1845 }
a3ed492f 1846 work = OPENSSL_strdup(cp);
52958608 1847 if (work == NULL) {
57c05c57
DDO
1848 BIO_printf(bio_err, "%s: Error copying %s name input\n",
1849 opt_getprog(), desc);
db4c08f0 1850 goto err;
52958608 1851 }
db4c08f0 1852
7e998a0f 1853 while (*cp != '\0') {
db4c08f0
RS
1854 char *bp = work;
1855 char *typestr = bp;
1856 unsigned char *valstr;
1857 int nid;
1858 int ismulti = nextismulti;
8cdb993d 1859
db4c08f0
RS
1860 nextismulti = 0;
1861
1862 /* Collect the type */
7e998a0f 1863 while (*cp != '\0' && *cp != '=')
db4c08f0 1864 *bp++ = *cp++;
57c05c57 1865 *bp++ = '\0';
db4c08f0 1866 if (*cp == '\0') {
0f113f3e 1867 BIO_printf(bio_err,
57c05c57
DDO
1868 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1869 opt_getprog(), typestr, desc);
db4c08f0 1870 goto err;
0f113f3e 1871 }
db4c08f0
RS
1872 ++cp;
1873
1874 /* Collect the value. */
1875 valstr = (unsigned char *)bp;
7e998a0f 1876 for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
5a0991d0 1877 /* unescaped '+' symbol string signals further member of multiRDN */
db4c08f0
RS
1878 if (canmulti && *cp == '+') {
1879 nextismulti = 1;
0f113f3e 1880 break;
db4c08f0
RS
1881 }
1882 if (*cp == '\\' && *++cp == '\0') {
1883 BIO_printf(bio_err,
57c05c57
DDO
1884 "%s: Escape character at end of %s name string\n",
1885 opt_getprog(), desc);
db4c08f0
RS
1886 goto err;
1887 }
0f113f3e
MC
1888 }
1889 *bp++ = '\0';
0f113f3e 1890
db4c08f0 1891 /* If not at EOS (must be + or /), move forward. */
7e998a0f 1892 if (*cp != '\0')
db4c08f0 1893 ++cp;
0f113f3e 1894
db4c08f0
RS
1895 /* Parse */
1896 nid = OBJ_txt2nid(typestr);
1897 if (nid == NID_undef) {
57c05c57
DDO
1898 BIO_printf(bio_err,
1899 "%s: Skipping unknown %s name attribute \"%s\"\n",
1900 opt_getprog(), desc, typestr);
5a0991d0
DDO
1901 if (ismulti)
1902 BIO_printf(bio_err,
1903 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
0f113f3e
MC
1904 continue;
1905 }
3d362f19
BK
1906 if (*valstr == '\0') {
1907 BIO_printf(bio_err,
57c05c57
DDO
1908 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1909 opt_getprog(), desc, typestr);
3d362f19
BK
1910 continue;
1911 }
db4c08f0
RS
1912 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1913 valstr, strlen((char *)valstr),
52958608 1914 -1, ismulti ? -1 : 0)) {
7e998a0f 1915 ERR_print_errors(bio_err);
57c05c57
DDO
1916 BIO_printf(bio_err,
1917 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1287dabd 1918 opt_getprog(), desc, typestr, valstr);
db4c08f0 1919 goto err;
52958608 1920 }
0f113f3e
MC
1921 }
1922
a3ed492f 1923 OPENSSL_free(work);
0f113f3e
MC
1924 return n;
1925
db4c08f0 1926 err:
0f113f3e 1927 X509_NAME_free(n);
a3ed492f 1928 OPENSSL_free(work);
0f113f3e 1929 return NULL;
6d5ffb59
RL
1930}
1931
0f113f3e
MC
1932/*
1933 * Read whole contents of a BIO into an allocated memory buffer and return
1934 * it.
a9164153
DSH
1935 */
1936
1937int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
0f113f3e
MC
1938{
1939 BIO *mem;
1940 int len, ret;
1941 unsigned char tbuf[1024];
bde136c8 1942
0f113f3e 1943 mem = BIO_new(BIO_s_mem());
96487cdd 1944 if (mem == NULL)
0f113f3e
MC
1945 return -1;
1946 for (;;) {
1947 if ((maxlen != -1) && maxlen < 1024)
1948 len = maxlen;
1949 else
1950 len = 1024;
1951 len = BIO_read(in, tbuf, len);
0c20802c
VD
1952 if (len < 0) {
1953 BIO_free(mem);
1954 return -1;
1955 }
1956 if (len == 0)
0f113f3e
MC
1957 break;
1958 if (BIO_write(mem, tbuf, len) != len) {
1959 BIO_free(mem);
1960 return -1;
1961 }
1962 maxlen -= len;
1963
1964 if (maxlen == 0)
1965 break;
1966 }
1967 ret = BIO_get_mem_data(mem, (char **)out);
1968 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1969 BIO_free(mem);
1970 return ret;
1971}
a9164153 1972
0c20802c 1973int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
0f113f3e 1974{
3d0b5678 1975 int rv = 0;
0f113f3e 1976 char *stmp, *vtmp = NULL;
3d0b5678 1977
7644a9ae 1978 stmp = OPENSSL_strdup(value);
3d0b5678 1979 if (stmp == NULL)
0f113f3e
MC
1980 return -1;
1981 vtmp = strchr(stmp, ':');
3d0b5678
MC
1982 if (vtmp == NULL)
1983 goto err;
1984
1985 *vtmp = 0;
1986 vtmp++;
0f113f3e 1987 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
3d0b5678
MC
1988
1989 err:
0f113f3e
MC
1990 OPENSSL_free(stmp);
1991 return rv;
1992}
a2318e86 1993
ecf3a1fb 1994static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
0f113f3e
MC
1995{
1996 X509_POLICY_NODE *node;
1997 int i;
ecf3a1fb
RS
1998
1999 BIO_printf(bio_err, "%s Policies:", name);
0f113f3e 2000 if (nodes) {
ecf3a1fb 2001 BIO_puts(bio_err, "\n");
0f113f3e
MC
2002 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
2003 node = sk_X509_POLICY_NODE_value(nodes, i);
ecf3a1fb 2004 X509_POLICY_NODE_print(bio_err, node, 2);
0f113f3e 2005 }
2234212c 2006 } else {
ecf3a1fb 2007 BIO_puts(bio_err, " <empty>\n");
2234212c 2008 }
0f113f3e 2009}
c431798e 2010
ecf3a1fb 2011void policies_print(X509_STORE_CTX *ctx)
0f113f3e
MC
2012{
2013 X509_POLICY_TREE *tree;
2014 int explicit_policy;
8cdb993d 2015
0f113f3e
MC
2016 tree = X509_STORE_CTX_get0_policy_tree(ctx);
2017 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2018
ecf3a1fb 2019 BIO_printf(bio_err, "Require explicit Policy: %s\n",
0f113f3e
MC
2020 explicit_policy ? "True" : "False");
2021
ecf3a1fb
RS
2022 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
2023 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
0f113f3e 2024}
ffa10187 2025
3a83462d
MC
2026/*-
2027 * next_protos_parse parses a comma separated list of strings into a string
71fa4513
BL
2028 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2029 * outlen: (output) set to the length of the resulting buffer on success.
2030 * err: (maybe NULL) on failure, an error message line is written to this BIO.
8483a003 2031 * in: a NUL terminated string like "abc,def,ghi"
71fa4513 2032 *
8483a003 2033 * returns: a malloc'd buffer or NULL on failure.
71fa4513 2034 */
817cd0d5 2035unsigned char *next_protos_parse(size_t *outlen, const char *in)
0f113f3e
MC
2036{
2037 size_t len;
2038 unsigned char *out;
2039 size_t i, start = 0;
e78253f2 2040 size_t skipped = 0;
0f113f3e
MC
2041
2042 len = strlen(in);
e78253f2 2043 if (len == 0 || len >= 65535)
0f113f3e
MC
2044 return NULL;
2045
e78253f2 2046 out = app_malloc(len + 1, "NPN buffer");
0f113f3e
MC
2047 for (i = 0; i <= len; ++i) {
2048 if (i == len || in[i] == ',') {
e78253f2
VD
2049 /*
2050 * Zero-length ALPN elements are invalid on the wire, we could be
2051 * strict and reject the entire string, but just ignoring extra
2052 * commas seems harmless and more friendly.
2053 *
2054 * Every comma we skip in this way puts the input buffer another
2055 * byte ahead of the output buffer, so all stores into the output
2056 * buffer need to be decremented by the number commas skipped.
2057 */
2058 if (i == start) {
2059 ++start;
2060 ++skipped;
2061 continue;
2062 }
0f113f3e
MC
2063 if (i - start > 255) {
2064 OPENSSL_free(out);
2065 return NULL;
2066 }
8cdb993d 2067 out[start - skipped] = (unsigned char)(i - start);
0f113f3e 2068 start = i + 1;
2234212c 2069 } else {
e78253f2 2070 out[i + 1 - skipped] = in[i];
2234212c 2071 }
0f113f3e
MC
2072 }
2073
e78253f2
VD
2074 if (len <= skipped) {
2075 OPENSSL_free(out);
2076 return NULL;
2077 }
2078
2079 *outlen = len + 1 - skipped;
0f113f3e
MC
2080 return out;
2081}
71fa4513 2082
8cdb993d
DDO
2083int check_cert_attributes(BIO *bio, X509 *x, const char *checkhost,
2084 const char *checkemail, const char *checkip,
2085 int print)
0f113f3e 2086{
9567fd38
RK
2087 int valid_host = 0;
2088 int valid_mail = 0;
2089 int valid_ip = 0;
2090 int ret = 1;
2091
0f113f3e 2092 if (x == NULL)
9567fd38
RK
2093 return 0;
2094
2095 if (checkhost != NULL) {
2096 valid_host = X509_check_host(x, checkhost, 0, 0, NULL);
2097 if (print)
2098 BIO_printf(bio, "Hostname %s does%s match certificate\n",
2099 checkhost, valid_host == 1 ? "" : " NOT");
2100 ret = ret && valid_host;
0f113f3e
MC
2101 }
2102
9567fd38
RK
2103 if (checkemail != NULL) {
2104 valid_mail = X509_check_email(x, checkemail, 0, 0);
2105 if (print)
2106 BIO_printf(bio, "Email %s does%s match certificate\n",
2107 checkemail, valid_mail ? "" : " NOT");
2108 ret = ret && valid_mail;
0f113f3e
MC
2109 }
2110
9567fd38 2111 if (checkip != NULL) {
8cdb993d 2112 valid_ip = X509_check_ip_asc(x, checkip, 0);
9567fd38
RK
2113 if (print)
2114 BIO_printf(bio, "IP %s does%s match certificate\n",
8cdb993d 2115 checkip, valid_ip ? "" : " NOT");
9567fd38 2116 ret = ret && valid_ip;
0f113f3e 2117 }
9567fd38
RK
2118
2119 return ret;
0f113f3e 2120}
a70da5b3 2121
6c9515b7
DDO
2122static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
2123{
2124 int i;
2125
2126 if (opts == NULL)
2127 return 1;
2128
2129 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2130 char *opt = sk_OPENSSL_STRING_value(opts, i);
8cdb993d 2131
6c9515b7
DDO
2132 if (pkey_ctrl_string(pkctx, opt) <= 0) {
2133 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2134 ERR_print_errors(bio_err);
2135 return 0;
2136 }
2137 }
2138
2139 return 1;
2140}
2141
2142static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
2143{
2144 int i;
2145
2146 if (opts == NULL)
2147 return 1;
2148
2149 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2150 char *opt = sk_OPENSSL_STRING_value(opts, i);
8cdb993d 2151
6c9515b7
DDO
2152 if (x509_ctrl_string(x, opt) <= 0) {
2153 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2154 ERR_print_errors(bio_err);
2155 return 0;
2156 }
2157 }
2158
2159 return 1;
2160}
2161
2162static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
2163{
2164 int i;
2165
2166 if (opts == NULL)
2167 return 1;
2168
2169 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2170 char *opt = sk_OPENSSL_STRING_value(opts, i);
8cdb993d 2171
6c9515b7
DDO
2172 if (x509_req_ctrl_string(x, opt) <= 0) {
2173 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2174 ERR_print_errors(bio_err);
2175 return 0;
2176 }
2177 }
2178
2179 return 1;
2180}
2181
2182static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
91034b68 2183 const char *md, STACK_OF(OPENSSL_STRING) *sigopts)
6c9515b7
DDO
2184{
2185 EVP_PKEY_CTX *pkctx = NULL;
91034b68 2186 char def_md[80];
6c9515b7
DDO
2187
2188 if (ctx == NULL)
2189 return 0;
2190 /*
91034b68 2191 * EVP_PKEY_get_default_digest_name() returns 2 if the digest is mandatory
6c9515b7
DDO
2192 * for this algorithm.
2193 */
91034b68
PG
2194 if (EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2
2195 && strcmp(def_md, "UNDEF") == 0) {
6c9515b7
DDO
2196 /* The signing algorithm requires there to be no digest */
2197 md = NULL;
2198 }
91034b68
PG
2199
2200 return EVP_DigestSignInit_ex(ctx, &pkctx, md, app_get0_libctx(),
2201 app_get0_propq(), pkey, NULL)
6c9515b7
DDO
2202 && do_pkey_ctx_init(pkctx, sigopts);
2203}
2204
ec2bfb7d
DDO
2205static int adapt_keyid_ext(X509 *cert, X509V3_CTX *ext_ctx,
2206 const char *name, const char *value, int add_default)
2207{
2208 const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2209 X509_EXTENSION *new_ext = X509V3_EXT_nconf(NULL, ext_ctx, name, value);
2210 int idx, rv = 0;
2211
2212 if (new_ext == NULL)
2213 return rv;
2214
2215 idx = X509v3_get_ext_by_OBJ(exts, X509_EXTENSION_get_object(new_ext), -1);
2216 if (idx >= 0) {
2217 X509_EXTENSION *found_ext = X509v3_get_ext(exts, idx);
adbd77f6
DDO
2218 ASN1_OCTET_STRING *encoded = X509_EXTENSION_get_data(found_ext);
2219 int disabled = ASN1_STRING_length(encoded) <= 2; /* indicating "none" */
ec2bfb7d
DDO
2220
2221 if (disabled) {
2222 X509_delete_ext(cert, idx);
2223 X509_EXTENSION_free(found_ext);
2224 } /* else keep existing key identifier, which might be outdated */
2225 rv = 1;
8cdb993d 2226 } else {
ec2bfb7d
DDO
2227 rv = !add_default || X509_add_ext(cert, new_ext, -1);
2228 }
2229 X509_EXTENSION_free(new_ext);
2230 return rv;
2231}
2232
adbd77f6
DDO
2233int cert_matches_key(const X509 *cert, const EVP_PKEY *pkey)
2234{
2235 int match;
2236
2237 ERR_set_mark();
2238 match = X509_check_private_key(cert, pkey);
2239 ERR_pop_to_mark();
2240 return match;
2241}
2242
ec2bfb7d 2243/* Ensure RFC 5280 compliance, adapt keyIDs as needed, and sign the cert info */
91034b68 2244int do_X509_sign(X509 *cert, EVP_PKEY *pkey, const char *md,
ec2bfb7d 2245 STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx)
6c9515b7
DDO
2246{
2247 const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2248 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
ec2bfb7d 2249 int self_sign;
6c9515b7
DDO
2250 int rv = 0;
2251
2252 if (sk_X509_EXTENSION_num(exts /* may be NULL */) > 0) {
2253 /* Prevent X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 */
cdf63a37 2254 if (!X509_set_version(cert, X509_VERSION_3))
6c9515b7
DDO
2255 goto end;
2256
ec2bfb7d 2257 /*
adbd77f6 2258 * Add default SKID before AKID such that AKID can make use of it
ec2bfb7d
DDO
2259 * in case the certificate is self-signed
2260 */
2261 /* Prevent X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER */
2262 if (!adapt_keyid_ext(cert, ext_ctx, "subjectKeyIdentifier", "hash", 1))
2263 goto end;
2264 /* Prevent X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER */
adbd77f6 2265 self_sign = cert_matches_key(cert, pkey);
ec2bfb7d
DDO
2266 if (!adapt_keyid_ext(cert, ext_ctx, "authorityKeyIdentifier",
2267 "keyid, issuer", !self_sign))
2268 goto end;
6c9515b7
DDO
2269 }
2270
2271 if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0)
2272 rv = (X509_sign_ctx(cert, mctx) > 0);
2273 end:
2274 EVP_MD_CTX_free(mctx);
2275 return rv;
2276}
2277
2278/* Sign the certificate request info */
91034b68 2279int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md,
6c9515b7
DDO
2280 STACK_OF(OPENSSL_STRING) *sigopts)
2281{
2282 int rv = 0;
2283 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2284
2285 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2286 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
2287 EVP_MD_CTX_free(mctx);
2288 return rv;
2289}
2290
2291/* Sign the CRL info */
91034b68 2292int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md,
6c9515b7
DDO
2293 STACK_OF(OPENSSL_STRING) *sigopts)
2294{
2295 int rv = 0;
2296 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2297
2298 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2299 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
2300 EVP_MD_CTX_free(mctx);
2301 return rv;
2302}
2303
bc42cf51
PH
2304/*
2305 * do_X509_verify returns 1 if the signature is valid,
2306 * 0 if the signature check fails, or -1 if error occurs.
2307 */
6c9515b7
DDO
2308int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
2309{
2310 int rv = 0;
2311
2312 if (do_x509_init(x, vfyopts) > 0)
bc42cf51
PH
2313 rv = X509_verify(x, pkey);
2314 else
2315 rv = -1;
6c9515b7
DDO
2316 return rv;
2317}
2318
bc42cf51
PH
2319/*
2320 * do_X509_REQ_verify returns 1 if the signature is valid,
2321 * 0 if the signature check fails, or -1 if error occurs.
2322 */
6c9515b7
DDO
2323int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
2324 STACK_OF(OPENSSL_STRING) *vfyopts)
2325{
2326 int rv = 0;
2327
2328 if (do_x509_req_init(x, vfyopts) > 0)
8cdb993d 2329 rv = X509_REQ_verify_ex(x, pkey, app_get0_libctx(), app_get0_propq());
bc42cf51
PH
2330 else
2331 rv = -1;
6c9515b7
DDO
2332 return rv;
2333}
2334
0090a686
DSH
2335/* Get first http URL from a DIST_POINT structure */
2336
2337static const char *get_dp_url(DIST_POINT *dp)
0f113f3e
MC
2338{
2339 GENERAL_NAMES *gens;
2340 GENERAL_NAME *gen;
2341 int i, gtype;
2342 ASN1_STRING *uri;
8cdb993d 2343
0f113f3e
MC
2344 if (!dp->distpoint || dp->distpoint->type != 0)
2345 return NULL;
2346 gens = dp->distpoint->name.fullname;
2347 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2348 gen = sk_GENERAL_NAME_value(gens, i);
2349 uri = GENERAL_NAME_get0_value(gen, &gtype);
2350 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
17ebf85a 2351 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
9498dac4
DDO
2352
2353 if (IS_HTTP(uptr)) /* can/should not use HTTPS here */
0f113f3e
MC
2354 return uptr;
2355 }
2356 }
2357 return NULL;
2358}
2359
2360/*
2361 * Look through a CRLDP structure and attempt to find an http URL to
2362 * downloads a CRL from.
0090a686
DSH
2363 */
2364
2365static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
0f113f3e
MC
2366{
2367 int i;
2368 const char *urlptr = NULL;
8cdb993d 2369
0f113f3e
MC
2370 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2371 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
8cdb993d 2372
0f113f3e 2373 urlptr = get_dp_url(dp);
e9d62da6 2374 if (urlptr != NULL)
d382e796 2375 return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP");
0f113f3e
MC
2376 }
2377 return NULL;
2378}
2379
2380/*
0aa87e86
DDO
2381 * Example of downloading CRLs from CRLDP:
2382 * not usable for real world as it always downloads and doesn't cache anything.
0090a686
DSH
2383 */
2384
8cc86b81
DDO
2385static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
2386 const X509_NAME *nm)
0f113f3e
MC
2387{
2388 X509 *x;
2389 STACK_OF(X509_CRL) *crls = NULL;
2390 X509_CRL *crl;
2391 STACK_OF(DIST_POINT) *crldp;
7e1b7485
RS
2392
2393 crls = sk_X509_CRL_new_null();
2394 if (!crls)
2395 return NULL;
0f113f3e
MC
2396 x = X509_STORE_CTX_get_current_cert(ctx);
2397 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2398 crl = load_crl_crldp(crldp);
2399 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
fe2b7dfd
MC
2400 if (!crl) {
2401 sk_X509_CRL_free(crls);
0f113f3e 2402 return NULL;
fe2b7dfd 2403 }
0f113f3e
MC
2404 sk_X509_CRL_push(crls, crl);
2405 /* Try to download delta CRL */
2406 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2407 crl = load_crl_crldp(crldp);
2408 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2409 if (crl)
2410 sk_X509_CRL_push(crls, crl);
2411 return crls;
2412}
0090a686
DSH
2413
2414void store_setup_crl_download(X509_STORE *st)
0f113f3e
MC
2415{
2416 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2417}
0090a686 2418
29f178bd
DDO
2419#ifndef OPENSSL_NO_SOCK
2420static const char *tls_error_hint(void)
2421{
2422 unsigned long err = ERR_peek_error();
2423
2424 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2425 err = ERR_peek_last_error();
2426 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2427 return NULL;
2428
2429 switch (ERR_GET_REASON(err)) {
2430 case SSL_R_WRONG_VERSION_NUMBER:
2431 return "The server does not support (a suitable version of) TLS";
2432 case SSL_R_UNKNOWN_PROTOCOL:
2433 return "The server does not support HTTPS";
2434 case SSL_R_CERTIFICATE_VERIFY_FAILED:
2435 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2436 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
2437 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2438 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
2439 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2440 default: /* no error or no hint available for error */
2441 return NULL;
2442 }
2443}
2444
2445/* HTTP callback function that supports TLS connection also via HTTPS proxy */
cdaf072f 2446BIO *app_http_tls_cb(BIO *bio, void *arg, int connect, int detail)
29f178bd 2447{
97b8c859
DDO
2448 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
2449 SSL_CTX *ssl_ctx = info->ssl_ctx;
2450
29f178bd 2451 if (connect && detail) { /* connecting with TLS */
ef203432
DDO
2452 SSL *ssl;
2453 BIO *sbio = NULL;
2454
068549f8 2455 /* adapt after fixing callback design flaw, see #17088 */
29f178bd 2456 if ((info->use_proxy
cdaf072f 2457 && !OSSL_HTTP_proxy_connect(bio, info->server, info->port,
29f178bd
DDO
2458 NULL, NULL, /* no proxy credentials */
2459 info->timeout, bio_err, opt_getprog()))
2460 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2461 return NULL;
2462 }
2463 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
2464 BIO_free(sbio);
2465 return NULL;
2466 }
2467
068549f8
DDO
2468 /* adapt after fixing callback design flaw, see #17088 */
2469 SSL_set_tlsext_host_name(ssl, info->server); /* not critical to do */
29f178bd
DDO
2470
2471 SSL_set_connect_state(ssl);
2472 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2473
cdaf072f 2474 bio = BIO_push(sbio, bio);
29f178bd 2475 }
cdaf072f
DDO
2476 if (!connect) {
2477 const char *hint;
2478 BIO *cbio;
2479
2480 if (!detail) { /* disconnecting after error */
2481 hint = tls_error_hint();
2482 if (hint != NULL)
2483 ERR_add_error_data(2, " : ", hint);
2484 }
97b8c859
DDO
2485 if (ssl_ctx != NULL) {
2486 (void)ERR_set_mark();
2487 BIO_ssl_shutdown(bio);
2488 cbio = BIO_pop(bio); /* connect+HTTP BIO */
2489 BIO_free(bio); /* SSL BIO */
2490 (void)ERR_pop_to_mark(); /* hide SSL_R_READ_BIO_NOT_SET etc. */
2491 bio = cbio;
2492 }
cdaf072f
DDO
2493 }
2494 return bio;
29f178bd
DDO
2495}
2496
ef203432
DDO
2497void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info)
2498{
2499 if (info != NULL) {
2500 SSL_CTX_free(info->ssl_ctx);
2501 OPENSSL_free(info);
2502 }
2503}
2504
29f178bd 2505ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
afe554c2 2506 const char *no_proxy, SSL_CTX *ssl_ctx,
29f178bd
DDO
2507 const STACK_OF(CONF_VALUE) *headers,
2508 long timeout, const char *expected_content_type,
2509 const ASN1_ITEM *it)
2510{
2511 APP_HTTP_TLS_INFO info;
2512 char *server;
2513 char *port;
2514 int use_ssl;
8f965908 2515 BIO *mem;
29f178bd
DDO
2516 ASN1_VALUE *resp = NULL;
2517
2518 if (url == NULL || it == NULL) {
9311d0c4 2519 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
29f178bd
DDO
2520 return NULL;
2521 }
2522
7932982b
DDO
2523 if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL /* userinfo */, &server, &port,
2524 NULL /* port_num, */, NULL, NULL, NULL))
29f178bd
DDO
2525 return NULL;
2526 if (use_ssl && ssl_ctx == NULL) {
a150f8e1
RL
2527 ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER,
2528 "missing SSL_CTX");
29f178bd
DDO
2529 goto end;
2530 }
2531
2532 info.server = server;
2533 info.port = port;
068549f8
DDO
2534 info.use_proxy = /* workaround for callback design flaw, see #17088 */
2535 OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl) != NULL;
29f178bd
DDO
2536 info.timeout = timeout;
2537 info.ssl_ctx = ssl_ctx;
8f965908
DDO
2538 mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2539 app_http_tls_cb, &info, 0 /* buf_size */, headers,
2540 expected_content_type, 1 /* expect_asn1 */,
647a5dbf 2541 OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout);
8f965908
DDO
2542 resp = ASN1_item_d2i_bio(it, mem, NULL);
2543 BIO_free(mem);
2544
29f178bd
DDO
2545 end:
2546 OPENSSL_free(server);
2547 OPENSSL_free(port);
2548 return resp;
2549
2550}
2551
2552ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2553 const char *path, const char *proxy,
afe554c2 2554 const char *no_proxy, SSL_CTX *ssl_ctx,
29f178bd
DDO
2555 const STACK_OF(CONF_VALUE) *headers,
2556 const char *content_type,
2557 ASN1_VALUE *req, const ASN1_ITEM *req_it,
82990287 2558 const char *expected_content_type,
29f178bd
DDO
2559 long timeout, const ASN1_ITEM *rsp_it)
2560{
068549f8 2561 int use_ssl = ssl_ctx != NULL;
29f178bd 2562 APP_HTTP_TLS_INFO info;
8f965908
DDO
2563 BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req);
2564 ASN1_VALUE *res;
29f178bd 2565
8f965908
DDO
2566 if (req_mem == NULL)
2567 return NULL;
068549f8 2568
29f178bd
DDO
2569 info.server = host;
2570 info.port = port;
068549f8
DDO
2571 info.use_proxy = /* workaround for callback design flaw, see #17088 */
2572 OSSL_HTTP_adapt_proxy(proxy, no_proxy, host, use_ssl) != NULL;
29f178bd
DDO
2573 info.timeout = timeout;
2574 info.ssl_ctx = ssl_ctx;
068549f8 2575 rsp = OSSL_HTTP_transfer(NULL, host, port, path, use_ssl,
8f965908
DDO
2576 proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2577 app_http_tls_cb, &info,
2578 0 /* buf_size */, headers, content_type, req_mem,
82990287 2579 expected_content_type, 1 /* expect_asn1 */,
647a5dbf 2580 OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout,
8f965908
DDO
2581 0 /* keep_alive */);
2582 BIO_free(req_mem);
2583 res = ASN1_item_d2i_bio(rsp_it, rsp, NULL);
2584 BIO_free(rsp);
2585 return res;
29f178bd
DDO
2586}
2587
2588#endif
2589
0a39d8f2
AP
2590/*
2591 * Platform-specific sections
2592 */
ffa10187 2593#if defined(_WIN32)
a1ad253f
AP
2594# ifdef fileno
2595# undef fileno
2596# define fileno(a) (int)_fileno(a)
2597# endif
2598
2599# include <windows.h>
2600# include <tchar.h>
2601
2602static int WIN32_rename(const char *from, const char *to)
0f113f3e
MC
2603{
2604 TCHAR *tfrom = NULL, *tto;
2605 DWORD err;
2606 int ret = 0;
2607
2608 if (sizeof(TCHAR) == 1) {
2609 tfrom = (TCHAR *)from;
2610 tto = (TCHAR *)to;
2611 } else { /* UNICODE path */
0f113f3e 2612 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
8cdb993d 2613
b1ad95e3 2614 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
0f113f3e
MC
2615 if (tfrom == NULL)
2616 goto err;
2617 tto = tfrom + flen;
8cdb993d 2618# if !defined(_WIN32_WCE) || _WIN32_WCE >= 101
0f113f3e
MC
2619 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2620# endif
2621 for (i = 0; i < flen; i++)
2622 tfrom[i] = (TCHAR)from[i];
8cdb993d 2623# if !defined(_WIN32_WCE) || _WIN32_WCE >= 101
0f113f3e
MC
2624 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2625# endif
2626 for (i = 0; i < tlen; i++)
2627 tto[i] = (TCHAR)to[i];
2628 }
2629
2630 if (MoveFile(tfrom, tto))
2631 goto ok;
2632 err = GetLastError();
2633 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2634 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2635 goto ok;
2636 err = GetLastError();
2637 }
2638 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2639 errno = ENOENT;
2640 else if (err == ERROR_ACCESS_DENIED)
2641 errno = EACCES;
2642 else
2643 errno = EINVAL; /* we could map more codes... */
2644 err:
2645 ret = -1;
2646 ok:
2647 if (tfrom != NULL && tfrom != (TCHAR *)from)
2648 free(tfrom);
2649 return ret;
2650}
0a39d8f2
AP
2651#endif
2652
2653/* app_tminterval section */
2654#if defined(_WIN32)
0f113f3e
MC
2655double app_tminterval(int stop, int usertime)
2656{
2657 FILETIME now;
2658 double ret = 0;
2659 static ULARGE_INTEGER tmstart;
2660 static int warning = 1;
8cdb993d 2661 int use_GetSystemTime = 1;
0f113f3e
MC
2662# ifdef _WIN32_WINNT
2663 static HANDLE proc = NULL;
2664
2665 if (proc == NULL) {
2666 if (check_winnt())
2667 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2668 GetCurrentProcessId());
2669 if (proc == NULL)
2670 proc = (HANDLE) - 1;
2671 }
2672
2673 if (usertime && proc != (HANDLE) - 1) {
2674 FILETIME junk;
8cdb993d 2675
0f113f3e 2676 GetProcessTimes(proc, &junk, &junk, &junk, &now);
8cdb993d
DDO
2677 use_GetSystemTime = 0;
2678 }
0f113f3e 2679# endif
8cdb993d 2680 if (use_GetSystemTime) {
0f113f3e 2681 SYSTEMTIME systime;
9135fddb 2682
0f113f3e
MC
2683 if (usertime && warning) {
2684 BIO_printf(bio_err, "To get meaningful results, run "
2685 "this program on idle system.\n");
2686 warning = 0;
2687 }
2688 GetSystemTime(&systime);
2689 SystemTimeToFileTime(&systime, &now);
2690 }
9135fddb 2691
0f113f3e
MC
2692 if (stop == TM_START) {
2693 tmstart.u.LowPart = now.dwLowDateTime;
2694 tmstart.u.HighPart = now.dwHighDateTime;
2695 } else {
2696 ULARGE_INTEGER tmstop;
9135fddb 2697
0f113f3e
MC
2698 tmstop.u.LowPart = now.dwLowDateTime;
2699 tmstop.u.HighPart = now.dwHighDateTime;
9135fddb 2700
0f113f3e
MC
2701 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2702 }
9135fddb 2703
26a7d938 2704 return ret;
0f113f3e 2705}
5c8b7b4c 2706#elif defined(OPENSSL_SYS_VXWORKS)
0f113f3e 2707# include <time.h>
0a39d8f2 2708
0f113f3e
MC
2709double app_tminterval(int stop, int usertime)
2710{
2711 double ret = 0;
2712# ifdef CLOCK_REALTIME
2713 static struct timespec tmstart;
2714 struct timespec now;
2715# else
2716 static unsigned long tmstart;
2717 unsigned long now;
2718# endif
2719 static int warning = 1;
2720
2721 if (usertime && warning) {
2722 BIO_printf(bio_err, "To get meaningful results, run "
2723 "this program on idle system.\n");
2724 warning = 0;
2725 }
2726# ifdef CLOCK_REALTIME
2727 clock_gettime(CLOCK_REALTIME, &now);
2728 if (stop == TM_START)
2729 tmstart = now;
2730 else
2731 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2732 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2733# else
2734 now = tickGet();
2735 if (stop == TM_START)
2736 tmstart = now;
2737 else
2738 ret = (now - tmstart) / (double)sysClkRateGet();
2739# endif
26a7d938 2740 return ret;
0f113f3e 2741}
0a39d8f2 2742
0f113f3e
MC
2743#elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2744# include <sys/times.h>
0a39d8f2 2745
0f113f3e
MC
2746double app_tminterval(int stop, int usertime)
2747{
2748 double ret = 0;
db71d315 2749 struct tms rus;
2bd928a1
TM
2750 clock_t now = times(&rus);
2751 static clock_t tmstart;
0f113f3e
MC
2752
2753 if (usertime)
2754 now = rus.tms_utime;
2755
2234212c 2756 if (stop == TM_START) {
0f113f3e 2757 tmstart = now;
2234212c 2758 } else {
2bd928a1 2759 long int tck = sysconf(_SC_CLK_TCK);
8cdb993d 2760
0f113f3e
MC
2761 ret = (now - tmstart) / (double)tck;
2762 }
2763
26a7d938 2764 return ret;
0f113f3e 2765}
0a39d8f2 2766
0f113f3e
MC
2767#else
2768# include <sys/time.h>
2769# include <sys/resource.h>
0a39d8f2 2770
0f113f3e
MC
2771double app_tminterval(int stop, int usertime)
2772{
2773 double ret = 0;
2774 struct rusage rus;
2775 struct timeval now;
2776 static struct timeval tmstart;
2777
2778 if (usertime)
2779 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2780 else
2781 gettimeofday(&now, NULL);
2782
2783 if (stop == TM_START)
2784 tmstart = now;
2785 else
2786 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2787 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2788
2789 return ret;
2790}
0a39d8f2 2791#endif
a1ad253f 2792
8cdb993d 2793int app_access(const char *name, int flag)
7e1b7485
RS
2794{
2795#ifdef _WIN32
2796 return _access(name, flag);
2797#else
2798 return access(name, flag);
2799#endif
2800}
2801
ffa10187 2802int app_isdir(const char *name)
0f113f3e 2803{
a43ce58f 2804 return opt_isdir(name);
0f113f3e 2805}
ffa10187 2806
0a39d8f2 2807/* raw_read|write section */
51e5133d
RL
2808#if defined(__VMS)
2809# include "vms_term_sock.h"
2810static int stdin_sock = -1;
2811
2812static void close_stdin_sock(void)
2813{
8cdb993d 2814 TerminalSocket(TERM_SOCK_DELETE, &stdin_sock);
51e5133d
RL
2815}
2816
2817int fileno_stdin(void)
2818{
2819 if (stdin_sock == -1) {
2820 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2821 atexit(close_stdin_sock);
2822 }
2823
2824 return stdin_sock;
2825}
2826#else
2827int fileno_stdin(void)
2828{
2829 return fileno(stdin);
2830}
2831#endif
2832
2833int fileno_stdout(void)
2834{
2835 return fileno(stdout);
2836}
2837
ffa10187 2838#if defined(_WIN32) && defined(STD_INPUT_HANDLE)
0f113f3e
MC
2839int raw_read_stdin(void *buf, int siz)
2840{
2841 DWORD n;
8cdb993d 2842
0f113f3e 2843 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
26a7d938 2844 return n;
0f113f3e 2845 else
26a7d938 2846 return -1;
0f113f3e 2847}
51e5133d 2848#elif defined(__VMS)
2234212c 2849# include <sys/socket.h>
a19228b7 2850
51e5133d
RL
2851int raw_read_stdin(void *buf, int siz)
2852{
2853 return recv(fileno_stdin(), buf, siz, 0);
2854}
ffa10187 2855#else
08073700
RB
2856# if defined(__TANDEM)
2857# if defined(OPENSSL_TANDEM_FLOSS)
2858# include <floss.h(floss_read)>
2859# endif
2860# endif
0f113f3e
MC
2861int raw_read_stdin(void *buf, int siz)
2862{
51e5133d 2863 return read(fileno_stdin(), buf, siz);
0f113f3e 2864}
ffa10187
AP
2865#endif
2866
2867#if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
0f113f3e
MC
2868int raw_write_stdout(const void *buf, int siz)
2869{
2870 DWORD n;
8cdb993d 2871
0f113f3e 2872 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
26a7d938 2873 return n;
0f113f3e 2874 else
26a7d938 2875 return -1;
0f113f3e 2876}
8cdb993d
DDO
2877#elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) \
2878 && defined(_SPT_MODEL_)
08073700
RB
2879# if defined(__TANDEM)
2880# if defined(OPENSSL_TANDEM_FLOSS)
2881# include <floss.h(floss_write)>
2882# endif
2883# endif
1287dabd 2884int raw_write_stdout(const void *buf, int siz)
08073700 2885{
8cdb993d 2886 return write(fileno(stdout), (void *)buf, siz);
08073700 2887}
ffa10187 2888#else
08073700
RB
2889# if defined(__TANDEM)
2890# if defined(OPENSSL_TANDEM_FLOSS)
2891# include <floss.h(floss_write)>
2892# endif
2893# endif
0f113f3e
MC
2894int raw_write_stdout(const void *buf, int siz)
2895{
51e5133d 2896 return write(fileno_stdout(), buf, siz);
0f113f3e 2897}
ffa10187 2898#endif
a412b891
RL
2899
2900/*
a43ce58f 2901 * Centralized handling of input and output files with format specification
a412b891
RL
2902 * The format is meant to show what the input and output is supposed to be,
2903 * and is therefore a show of intent more than anything else. However, it
a43ce58f 2904 * does impact behavior on some platforms, such as differentiating between
a412b891
RL
2905 * text and binary input/output on non-Unix platforms
2906 */
a60994df 2907BIO *dup_bio_in(int format)
a412b891 2908{
a60994df 2909 return BIO_new_fp(stdin,
a43ce58f 2910 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
a60994df
RL
2911}
2912
2913BIO *dup_bio_out(int format)
2914{
2915 BIO *b = BIO_new_fp(stdout,
a43ce58f 2916 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
71bb86f0
RL
2917 void *prefix = NULL;
2918
a412b891 2919#ifdef OPENSSL_SYS_VMS
a43ce58f 2920 if (FMT_istext(format))
a60994df 2921 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
149bd5d6 2922#endif
71bb86f0 2923
682b444f
RL
2924 if (FMT_istext(format)
2925 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
e79ae962
RL
2926 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2927 BIO_set_prefix(b, prefix);
71bb86f0
RL
2928 }
2929
149bd5d6
RL
2930 return b;
2931}
2932
2933BIO *dup_bio_err(int format)
2934{
2935 BIO *b = BIO_new_fp(stderr,
a43ce58f 2936 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
8cdb993d 2937
149bd5d6 2938#ifdef OPENSSL_SYS_VMS
a43ce58f 2939 if (FMT_istext(format))
149bd5d6 2940 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
a412b891
RL
2941#endif
2942 return b;
2943}
2944
2945void unbuffer(FILE *fp)
2946{
90dbd250
RL
2947/*
2948 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2949 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2950 * However, we trust that the C RTL will never give us a FILE pointer
2951 * above the first 4 GB of memory, so we simply turn off the warning
2952 * temporarily.
2953 */
2954#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2955# pragma environment save
2956# pragma message disable maylosedata2
2957#endif
a412b891 2958 setbuf(fp, NULL);
90dbd250
RL
2959#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2960# pragma environment restore
2961#endif
a412b891
RL
2962}
2963
2964static const char *modestr(char mode, int format)
2965{
2966 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2967
2968 switch (mode) {
2969 case 'a':
a43ce58f 2970 return FMT_istext(format) ? "a" : "ab";
a412b891 2971 case 'r':
a43ce58f 2972 return FMT_istext(format) ? "r" : "rb";
a412b891 2973 case 'w':
a43ce58f 2974 return FMT_istext(format) ? "w" : "wb";
a412b891
RL
2975 }
2976 /* The assert above should make sure we never reach this point */
2977 return NULL;
2978}
2979
2980static const char *modeverb(char mode)
2981{
2982 switch (mode) {
2983 case 'a':
2984 return "appending";
2985 case 'r':
2986 return "reading";
2987 case 'w':
2988 return "writing";
2989 }
2990 return "(doing something)";
2991}
2992
2993/*
2994 * Open a file for writing, owner-read-only.
2995 */
2996BIO *bio_open_owner(const char *filename, int format, int private)
2997{
2998 FILE *fp = NULL;
2999 BIO *b = NULL;
2f0a5381
P
3000 int textmode, bflags;
3001#ifndef OPENSSL_NO_POSIX_IO
3002 int fd = -1, mode;
3003#endif
a412b891
RL
3004
3005 if (!private || filename == NULL || strcmp(filename, "-") == 0)
3006 return bio_open_default(filename, 'w', format);
3007
2f0a5381
P
3008 textmode = FMT_istext(format);
3009#ifndef OPENSSL_NO_POSIX_IO
a412b891 3010 mode = O_WRONLY;
2f0a5381 3011# ifdef O_CREAT
a412b891 3012 mode |= O_CREAT;
2f0a5381
P
3013# endif
3014# ifdef O_TRUNC
a412b891 3015 mode |= O_TRUNC;
2f0a5381 3016# endif
1cd5cc36 3017 if (!textmode) {
2f0a5381 3018# ifdef O_BINARY
a412b891 3019 mode |= O_BINARY;
2f0a5381 3020# elif defined(_O_BINARY)
a412b891 3021 mode |= _O_BINARY;
2f0a5381 3022# endif
a412b891
RL
3023 }
3024
2f0a5381 3025# ifdef OPENSSL_SYS_VMS
8cdb993d
DDO
3026 /*
3027 * VMS doesn't have O_BINARY, it just doesn't make sense. But,
fbd03b09
RL
3028 * it still needs to know that we're going binary, or fdopen()
3029 * will fail with "invalid argument"... so we tell VMS what the
3030 * context is.
3031 */
3032 if (!textmode)
3033 fd = open(filename, mode, 0600, "ctx=bin");
3034 else
2f0a5381 3035# endif
fbd03b09 3036 fd = open(filename, mode, 0600);
a412b891
RL
3037 if (fd < 0)
3038 goto err;
3039 fp = fdopen(fd, modestr('w', format));
2f0a5381
P
3040#else /* OPENSSL_NO_POSIX_IO */
3041 /* Have stdio but not Posix IO, do the best we can */
3042 fp = fopen(filename, modestr('w', format));
3043#endif /* OPENSSL_NO_POSIX_IO */
a412b891
RL
3044 if (fp == NULL)
3045 goto err;
3046 bflags = BIO_CLOSE;
1cd5cc36 3047 if (textmode)
a412b891
RL
3048 bflags |= BIO_FP_TEXT;
3049 b = BIO_new_fp(fp, bflags);
2f0a5381 3050 if (b != NULL)
a412b891
RL
3051 return b;
3052
3053 err:
3054 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
3055 opt_getprog(), filename, strerror(errno));
3056 ERR_print_errors(bio_err);
3057 /* If we have fp, then fdopen took over fd, so don't close both. */
2f0a5381 3058 if (fp != NULL)
a412b891 3059 fclose(fp);
2f0a5381 3060#ifndef OPENSSL_NO_POSIX_IO
a412b891
RL
3061 else if (fd >= 0)
3062 close(fd);
2f0a5381 3063#endif
a412b891
RL
3064 return NULL;
3065}
3066
3067static BIO *bio_open_default_(const char *filename, char mode, int format,
3068 int quiet)
3069{
3070 BIO *ret;
3071
3072 if (filename == NULL || strcmp(filename, "-") == 0) {
a60994df 3073 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
a412b891
RL
3074 if (quiet) {
3075 ERR_clear_error();
3076 return ret;
3077 }
3078 if (ret != NULL)
3079 return ret;
3080 BIO_printf(bio_err,
3081 "Can't open %s, %s\n",
3082 mode == 'r' ? "stdin" : "stdout", strerror(errno));
3083 } else {
3084 ret = BIO_new_file(filename, modestr(mode, format));
3085 if (quiet) {
3086 ERR_clear_error();
3087 return ret;
3088 }
3089 if (ret != NULL)
3090 return ret;
3091 BIO_printf(bio_err,
15795943 3092 "Can't open \"%s\" for %s, %s\n",
a412b891
RL
3093 filename, modeverb(mode), strerror(errno));
3094 }
3095 ERR_print_errors(bio_err);
3096 return NULL;
3097}
3098
3099BIO *bio_open_default(const char *filename, char mode, int format)
3100{
3101 return bio_open_default_(filename, mode, format, 0);
3102}
3103
3104BIO *bio_open_default_quiet(const char *filename, char mode, int format)
3105{
3106 return bio_open_default_(filename, mode, format, 1);
3107}
3108
e1b9840e
MC
3109void wait_for_async(SSL *s)
3110{
d6e03b70
MC
3111 /* On Windows select only works for sockets, so we simply don't wait */
3112#ifndef OPENSSL_SYS_WINDOWS
ff75a257 3113 int width = 0;
e1b9840e 3114 fd_set asyncfds;
ff75a257
MC
3115 OSSL_ASYNC_FD *fds;
3116 size_t numfds;
0a345252 3117 size_t i;
e1b9840e 3118
ff75a257
MC
3119 if (!SSL_get_all_async_fds(s, NULL, &numfds))
3120 return;
3121 if (numfds == 0)
e1b9840e 3122 return;
589902b2 3123 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
ff75a257
MC
3124 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
3125 OPENSSL_free(fds);
0a345252 3126 return;
ff75a257 3127 }
e1b9840e 3128
e1b9840e 3129 FD_ZERO(&asyncfds);
0a345252
P
3130 for (i = 0; i < numfds; i++) {
3131 if (width <= (int)fds[i])
3132 width = (int)fds[i] + 1;
3133 openssl_fdset((int)fds[i], &asyncfds);
ff75a257 3134 }
e1b9840e 3135 select(width, (void *)&asyncfds, NULL, NULL, NULL);
0a345252 3136 OPENSSL_free(fds);
d6e03b70 3137#endif
e1b9840e 3138}
75dd6c1a
MC
3139
3140/* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
3141#if defined(OPENSSL_SYS_MSDOS)
3142int has_stdin_waiting(void)
3143{
3144# if defined(OPENSSL_SYS_WINDOWS)
3145 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
3146 DWORD events = 0;
3147 INPUT_RECORD inputrec;
3148 DWORD insize = 1;
3149 BOOL peeked;
3150
3151 if (inhand == INVALID_HANDLE_VALUE) {
3152 return 0;
3153 }
3154
3155 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
3156 if (!peeked) {
3157 /* Probably redirected input? _kbhit() does not work in this case */
3158 if (!feof(stdin)) {
3159 return 1;
3160 }
3161 return 0;
3162 }
3163# endif
3164 return _kbhit();
3165}
3166#endif
17ebf85a
DSH
3167
3168/* Corrupt a signature by modifying final byte */
a0754084 3169void corrupt_signature(const ASN1_STRING *signature)
17ebf85a 3170{
8cdb993d
DDO
3171 unsigned char *s = signature->data;
3172
3173 s[signature->length - 1] ^= 0x1;
17ebf85a 3174}
dc047d31
DSH
3175
3176int set_cert_times(X509 *x, const char *startdate, const char *enddate,
3177 int days)
3178{
dc047d31 3179 if (startdate == NULL || strcmp(startdate, "today") == 0) {
0b7347ef
DSH
3180 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
3181 return 0;
3182 } else {
04e62715 3183 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
0b7347ef 3184 return 0;
dc047d31 3185 }
dc047d31 3186 if (enddate == NULL) {
0b7347ef
DSH
3187 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
3188 == NULL)
3189 return 0;
04e62715 3190 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
0b7347ef 3191 return 0;
dc047d31 3192 }
0b7347ef 3193 return 1;
dc047d31 3194}
20967afb 3195
64713cb1
CN
3196int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
3197{
3198 int ret = 0;
3199 ASN1_TIME *tm = ASN1_TIME_new();
3200
3201 if (tm == NULL)
3202 goto end;
3203
3204 if (lastupdate == NULL) {
3205 if (X509_gmtime_adj(tm, 0) == NULL)
3206 goto end;
3207 } else {
3208 if (!ASN1_TIME_set_string_X509(tm, lastupdate))
3209 goto end;
3210 }
3211
3212 if (!X509_CRL_set1_lastUpdate(crl, tm))
3213 goto end;
3214
3215 ret = 1;
3216end:
3217 ASN1_TIME_free(tm);
3218 return ret;
3219}
3220
3221int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
3222 long days, long hours, long secs)
3223{
3224 int ret = 0;
3225 ASN1_TIME *tm = ASN1_TIME_new();
3226
3227 if (tm == NULL)
3228 goto end;
3229
3230 if (nextupdate == NULL) {
3231 if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
3232 goto end;
3233 } else {
3234 if (!ASN1_TIME_set_string_X509(tm, nextupdate))
3235 goto end;
3236 }
3237
3238 if (!X509_CRL_set1_nextUpdate(crl, tm))
3239 goto end;
3240
3241 ret = 1;
3242end:
3243 ASN1_TIME_free(tm);
3244 return ret;
3245}
3246
20967afb
RS
3247void make_uppercase(char *string)
3248{
3249 int i;
3250
3251 for (i = 0; string[i] != '\0'; i++)
3252 string[i] = toupper((unsigned char)string[i]);
3253}
a43ce58f 3254
95214b43
SL
3255OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
3256 const OSSL_PARAM *paramdefs)
3257{
3258 OSSL_PARAM *params = NULL;
3259 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
3260 size_t params_n;
3261 char *opt = "", *stmp, *vtmp = NULL;
e1dcac22 3262 int found = 1;
95214b43
SL
3263
3264 if (opts == NULL)
3265 return NULL;
3266
3267 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
3268 if (params == NULL)
3269 return NULL;
3270
3271 for (params_n = 0; params_n < sz; params_n++) {
3272 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
3273 if ((stmp = OPENSSL_strdup(opt)) == NULL
3274 || (vtmp = strchr(stmp, ':')) == NULL)
3275 goto err;
3276 /* Replace ':' with 0 to terminate the string pointed to by stmp */
3277 *vtmp = 0;
3278 /* Skip over the separator so that vmtp points to the value */
3279 vtmp++;
3280 if (!OSSL_PARAM_allocate_from_text(&params[params_n], paramdefs,
e1dcac22 3281 stmp, vtmp, strlen(vtmp), &found))
95214b43
SL
3282 goto err;
3283 OPENSSL_free(stmp);
3284 }
3285 params[params_n] = OSSL_PARAM_construct_end();
3286 return params;
3287err:
3288 OPENSSL_free(stmp);
e1dcac22
P
3289 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
3290 opt);
95214b43
SL
3291 ERR_print_errors(bio_err);
3292 app_params_free(params);
3293 return NULL;
3294}
3295
3296void app_params_free(OSSL_PARAM *params)
3297{
3298 int i;
3299
3300 if (params != NULL) {
3301 for (i = 0; params[i].key != NULL; ++i)
3302 OPENSSL_free(params[i].data);
3303 OPENSSL_free(params);
3304 }
3305}
a7e4ca5b
DDO
3306
3307EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose)
3308{
3309 EVP_PKEY *res = NULL;
3310
3311 if (verbose && alg != NULL) {
3312 BIO_printf(bio_err, "Generating %s key", alg);
3313 if (bits > 0)
3314 BIO_printf(bio_err, " with %d bits\n", bits);
3315 else
3316 BIO_printf(bio_err, "\n");
3317 }
3318 if (!RAND_status())
3319 BIO_printf(bio_err, "Warning: generating random key material may take a long time\n"
3320 "if the system has a poor entropy source\n");
3321 if (EVP_PKEY_keygen(ctx, &res) <= 0)
3322 app_bail_out("%s: Error generating %s key\n", opt_getprog(),
3323 alg != NULL ? alg : "asymmetric");
3324 return res;
3325}
3326
3327EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg)
3328{
3329 EVP_PKEY *res = NULL;
3330
3331 if (!RAND_status())
3332 BIO_printf(bio_err, "Warning: generating random key parameters may take a long time\n"
3333 "if the system has a poor entropy source\n");
3334 if (EVP_PKEY_paramgen(ctx, &res) <= 0)
3335 app_bail_out("%s: Generating %s key parameters failed\n",
3336 opt_getprog(), alg != NULL ? alg : "asymmetric");
3337 return res;
3338}
ff215713
P
3339
3340/*
3341 * Return non-zero if the legacy path is still an option.
3342 * This decision is based on the global command line operations and the
3343 * behaviour thus far.
3344 */
3345int opt_legacy_okay(void)
3346{
3347 int provider_options = opt_provider_option_given();
3348 int libctx = app_get0_libctx() != NULL || app_get0_propq() != NULL;
3349#ifndef OPENSSL_NO_ENGINE
3350 ENGINE *e = ENGINE_get_first();
3351
3352 if (e != NULL) {
3353 ENGINE_free(e);
3354 return 1;
3355 }
3356#endif
3357 /*
3358 * Having a provider option specified or a custom library context or
3359 * property query, is a sure sign we're not using legacy.
3360 */
3361 if (provider_options || libctx)
3362 return 0;
3363 return 1;
3364}