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