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