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