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