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