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