]> git.ipfire.org Git - thirdparty/openssl.git/blame - apps/lib/apps.c
apps: remove TODOs
[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>
a7e4ca5b 38#include <openssl/rand.h>
f0eae953 39#include <openssl/bn.h>
7e1b7485 40#include <openssl/ssl.h>
0b27381f 41#include <openssl/store.h>
d382e796 42#include <openssl/core_names.h>
0b27381f 43#include "s_apps.h"
d610d27f 44#include "apps.h"
d610d27f 45
a1ad253f
AP
46#ifdef _WIN32
47static int WIN32_rename(const char *from, const char *to);
0f113f3e 48# define rename(from,to) WIN32_rename((from),(to))
a1ad253f
AP
49#endif
50
d0cf719e
DMSP
51#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
52# include <conio.h>
53#endif
54
96d4ec67 55#if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) || defined(__BORLANDC__)
d0cf719e
DMSP
56# define _kbhit kbhit
57#endif
58
15795943
DDO
59static BIO *bio_open_default_(const char *filename, char mode, int format,
60 int quiet);
61
62ca1565
DO
62#define PASS_SOURCE_SIZE_MAX 4
63
852c2ed2 64DEFINE_STACK_OF(CONF)
852c2ed2 65
8ca533e3 66typedef struct {
0f113f3e
MC
67 const char *name;
68 unsigned long flag;
69 unsigned long mask;
8ca533e3
DSH
70} NAME_EX_TBL;
71
b4250010 72static OSSL_LIB_CTX *app_libctx = NULL;
ae89578b 73
0f113f3e
MC
74static int set_table_opts(unsigned long *flags, const char *arg,
75 const NAME_EX_TBL * in_tbl);
76static int set_multi_opts(unsigned long *flags, const char *arg,
77 const NAME_EX_TBL * in_tbl);
8ca533e3 78
d02b48c6 79int app_init(long mesgwin);
0f113f3e 80
7e1b7485 81int chopup_args(ARGS *arg, char *buf)
0f113f3e 82{
7e1b7485 83 int quoted;
4c9b0a03 84 char c = '\0', *p = NULL;
0f113f3e 85
7e1b7485
RS
86 arg->argc = 0;
87 if (arg->size == 0) {
88 arg->size = 20;
b4faea50 89 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
0f113f3e 90 }
0f113f3e 91
7e1b7485
RS
92 for (p = buf;;) {
93 /* Skip whitespace. */
18295f0c 94 while (*p && isspace(_UC(*p)))
0f113f3e 95 p++;
12a765a5 96 if (*p == '\0')
0f113f3e
MC
97 break;
98
99 /* The start of something good :-) */
7e1b7485 100 if (arg->argc >= arg->size) {
7c0ef843 101 char **tmp;
7e1b7485 102 arg->size += 20;
7c0ef843
DSH
103 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
104 if (tmp == NULL)
0f113f3e 105 return 0;
7c0ef843 106 arg->argv = tmp;
0f113f3e 107 }
7e1b7485
RS
108 quoted = *p == '\'' || *p == '"';
109 if (quoted)
110 c = *p++;
111 arg->argv[arg->argc++] = p;
0f113f3e
MC
112
113 /* now look for the end of this */
7e1b7485
RS
114 if (quoted) {
115 while (*p && *p != c)
0f113f3e 116 p++;
7e1b7485 117 *p++ = '\0';
0f113f3e 118 } else {
18295f0c 119 while (*p && !isspace(_UC(*p)))
0f113f3e 120 p++;
7e1b7485
RS
121 if (*p)
122 *p++ = '\0';
0f113f3e 123 }
0f113f3e 124 }
7e1b7485 125 arg->argv[arg->argc] = NULL;
208fb891 126 return 1;
0f113f3e 127}
d02b48c6
RE
128
129#ifndef APP_INIT
6b691a5c 130int app_init(long mesgwin)
0f113f3e 131{
208fb891 132 return 1;
0f113f3e 133}
d02b48c6 134#endif
53b1899e 135
fd3397fc
RL
136int ctx_set_verify_locations(SSL_CTX *ctx,
137 const char *CAfile, int noCAfile,
138 const char *CApath, int noCApath,
139 const char *CAstore, int noCAstore)
7e1b7485 140{
fd3397fc 141 if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
2b6bcb70
MC
142 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
143 return 0;
144 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
145 return 0;
fd3397fc
RL
146 if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
147 return 0;
2b6bcb70
MC
148
149 return 1;
150 }
fd3397fc
RL
151
152 if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
153 return 0;
154 if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
155 return 0;
156 if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
157 return 0;
158 return 1;
7e1b7485
RS
159}
160
b5369582
RP
161#ifndef OPENSSL_NO_CT
162
dd696a55
RP
163int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
164{
2234212c 165 if (path == NULL)
328f36c5 166 return SSL_CTX_set_default_ctlog_list_file(ctx);
dd696a55
RP
167
168 return SSL_CTX_set_ctlog_list_file(ctx, path);
169}
170
b5369582
RP
171#endif
172
b5c4209b
DB
173static unsigned long nmflag = 0;
174static char nmflag_set = 0;
175
176int set_nameopt(const char *arg)
954ef7ef 177{
b5c4209b
DB
178 int ret = set_name_ex(&nmflag, arg);
179
180 if (ret)
181 nmflag_set = 1;
182
183 return ret;
184}
54a656ef 185
b5c4209b
DB
186unsigned long get_nameopt(void)
187{
188 return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
189}
954ef7ef 190
b5c4209b
DB
191int dump_cert_text(BIO *out, X509 *x)
192{
46a11faf 193 print_name(out, "subject=", X509_get_subject_name(x));
b5c4209b 194 BIO_puts(out, "\n");
46a11faf 195 print_name(out, "issuer=", X509_get_issuer_name(x));
0f113f3e 196 BIO_puts(out, "\n");
54a656ef 197
0f113f3e 198 return 0;
954ef7ef 199}
a3fe382e 200
229446df
RS
201int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
202{
203 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
204}
205
a43ce58f 206
cc696296 207static char *app_get_pass(const char *arg, int keepbio);
a3fe382e 208
6d382c74
DDO
209char *get_passwd(const char *pass, const char *desc)
210{
211 char *result = NULL;
212
213 if (desc == NULL)
214 desc = "<unknown>";
215 if (!app_passwd(pass, NULL, &result, NULL))
216 BIO_printf(bio_err, "Error getting password for %s\n", desc);
217 if (pass != NULL && result == NULL) {
218 BIO_printf(bio_err,
219 "Trying plain input string (better precede with 'pass:')\n");
220 result = OPENSSL_strdup(pass);
221 if (result == NULL)
222 BIO_printf(bio_err, "Out of memory getting password for %s\n", desc);
223 }
224 return result;
225}
226
cc696296 227int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
a3fe382e 228{
229446df
RS
229 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
230
2234212c 231 if (arg1 != NULL) {
7e1b7485 232 *pass1 = app_get_pass(arg1, same);
2234212c 233 if (*pass1 == NULL)
0f113f3e 234 return 0;
2234212c 235 } else if (pass1 != NULL) {
0f113f3e 236 *pass1 = NULL;
2234212c
PY
237 }
238 if (arg2 != NULL) {
7e1b7485 239 *pass2 = app_get_pass(arg2, same ? 2 : 0);
2234212c 240 if (*pass2 == NULL)
0f113f3e 241 return 0;
2234212c 242 } else if (pass2 != NULL) {
0f113f3e 243 *pass2 = NULL;
2234212c 244 }
0f113f3e 245 return 1;
a3fe382e
DSH
246}
247
cc696296 248static char *app_get_pass(const char *arg, int keepbio)
a3fe382e 249{
0f113f3e 250 static BIO *pwdbio = NULL;
229446df 251 char *tmp, tpass[APP_PASS_LEN];
0f113f3e 252 int i;
86885c28 253
62ca1565 254 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
86885c28 255 if (strncmp(arg, "pass:", 5) == 0)
7644a9ae 256 return OPENSSL_strdup(arg + 5);
86885c28 257 if (strncmp(arg, "env:", 4) == 0) {
0f113f3e 258 tmp = getenv(arg + 4);
2234212c 259 if (tmp == NULL) {
229446df 260 BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
0f113f3e
MC
261 return NULL;
262 }
7644a9ae 263 return OPENSSL_strdup(tmp);
0f113f3e 264 }
2234212c 265 if (!keepbio || pwdbio == NULL) {
86885c28 266 if (strncmp(arg, "file:", 5) == 0) {
0f113f3e 267 pwdbio = BIO_new_file(arg + 5, "r");
2234212c 268 if (pwdbio == NULL) {
7e1b7485 269 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
0f113f3e
MC
270 return NULL;
271 }
eff7cb41 272#if !defined(_WIN32)
0f113f3e
MC
273 /*
274 * Under _WIN32, which covers even Win64 and CE, file
275 * descriptors referenced by BIO_s_fd are not inherited
276 * by child process and therefore below is not an option.
277 * It could have been an option if bss_fd.c was operating
278 * on real Windows descriptors, such as those obtained
279 * with CreateFile.
280 */
86885c28 281 } else if (strncmp(arg, "fd:", 3) == 0) {
0f113f3e
MC
282 BIO *btmp;
283 i = atoi(arg + 3);
284 if (i >= 0)
285 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
286 if ((i < 0) || !pwdbio) {
7e1b7485 287 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
0f113f3e
MC
288 return NULL;
289 }
290 /*
291 * Can't do BIO_gets on an fd BIO so add a buffering BIO
292 */
293 btmp = BIO_new(BIO_f_buffer());
294 pwdbio = BIO_push(btmp, pwdbio);
295#endif
86885c28 296 } else if (strcmp(arg, "stdin") == 0) {
a60994df 297 pwdbio = dup_bio_in(FORMAT_TEXT);
12a765a5 298 if (pwdbio == NULL) {
7e1b7485 299 BIO_printf(bio_err, "Can't open BIO for stdin\n");
0f113f3e
MC
300 return NULL;
301 }
302 } else {
62ca1565
DO
303 /* argument syntax error; do not reveal too much about arg */
304 tmp = strchr(arg, ':');
305 if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
306 BIO_printf(bio_err,
307 "Invalid password argument, missing ':' within the first %d chars\n",
308 PASS_SOURCE_SIZE_MAX + 1);
309 else
310 BIO_printf(bio_err,
311 "Invalid password argument, starting with \"%.*s\"\n",
312 (int)(tmp - arg + 1), arg);
0f113f3e
MC
313 return NULL;
314 }
315 }
316 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
317 if (keepbio != 1) {
318 BIO_free_all(pwdbio);
319 pwdbio = NULL;
320 }
321 if (i <= 0) {
7e1b7485 322 BIO_printf(bio_err, "Error reading password from BIO\n");
0f113f3e
MC
323 return NULL;
324 }
325 tmp = strchr(tpass, '\n');
2234212c 326 if (tmp != NULL)
0f113f3e 327 *tmp = 0;
7644a9ae 328 return OPENSSL_strdup(tpass);
a3fe382e 329}
90ae4673 330
b4250010 331OSSL_LIB_CTX *app_get0_libctx(void)
ae89578b
SL
332{
333 return app_libctx;
334}
335
7dc67708
PG
336static const char *app_propq = NULL;
337
338int app_set_propq(const char *arg)
339{
340 app_propq = arg;
341 return 1;
342}
343
6725682d
SL
344const char *app_get0_propq(void)
345{
7dc67708 346 return app_propq;
6725682d
SL
347}
348
b4250010 349OSSL_LIB_CTX *app_create_libctx(void)
ae89578b
SL
350{
351 /*
352 * Load the NULL provider into the default library context and create a
353 * library context which will then be used for any OPT_PROV options.
354 */
355 if (app_libctx == NULL) {
356
357 if (!app_provider_load(NULL, "null")) {
358 BIO_puts(bio_err, "Failed to create null provider\n");
359 return NULL;
360 }
b4250010 361 app_libctx = OSSL_LIB_CTX_new();
ae89578b
SL
362 }
363 if (app_libctx == NULL)
364 BIO_puts(bio_err, "Failed to create library context\n");
365 return app_libctx;
366}
367
bfa470a4 368CONF *app_load_config_bio(BIO *in, const char *filename)
cc01d217
RS
369{
370 long errorline = -1;
371 CONF *conf;
372 int i;
cc01d217 373
d8652be0 374 conf = NCONF_new_ex(app_libctx, NULL);
cc01d217 375 i = NCONF_load_bio(conf, in, &errorline);
cc01d217
RS
376 if (i > 0)
377 return conf;
378
bfa470a4
RL
379 if (errorline <= 0) {
380 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
381 } else {
382 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
383 errorline);
384 }
385 if (filename != NULL)
386 BIO_printf(bio_err, "config file \"%s\"\n", filename);
cc01d217 387 else
bfa470a4
RL
388 BIO_printf(bio_err, "config input");
389
cc01d217
RS
390 NCONF_free(conf);
391 return NULL;
392}
2234212c 393
15795943 394CONF *app_load_config_verbose(const char *filename, int verbose)
296f54ee 395{
15795943
DDO
396 if (verbose) {
397 if (*filename == '\0')
398 BIO_printf(bio_err, "No configuration used\n");
399 else
400 BIO_printf(bio_err, "Using configuration from %s\n", filename);
401 }
402 return app_load_config_internal(filename, 0);
296f54ee 403}
2234212c 404
15795943 405CONF *app_load_config_internal(const char *filename, int quiet)
296f54ee 406{
15795943 407 BIO *in = NULL; /* leads to empty config in case filename == "" */
296f54ee
RL
408 CONF *conf;
409
15795943
DDO
410 if (*filename != '\0'
411 && (in = bio_open_default_(filename, 'r', FORMAT_TEXT, quiet)) == NULL)
296f54ee 412 return NULL;
bfa470a4 413 conf = app_load_config_bio(in, filename);
296f54ee
RL
414 BIO_free(in);
415 return conf;
416}
417
418int app_load_modules(const CONF *config)
419{
420 CONF *to_free = NULL;
421
422 if (config == NULL)
dccd20d1 423 config = to_free = app_load_config_quiet(default_config_file);
296f54ee 424 if (config == NULL)
dccd20d1 425 return 1;
296f54ee
RL
426
427 if (CONF_modules_load(config, NULL, 0) <= 0) {
428 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
429 ERR_print_errors(bio_err);
430 NCONF_free(to_free);
431 return 0;
432 }
433 NCONF_free(to_free);
434 return 1;
435}
cc01d217 436
7e1b7485 437int add_oid_section(CONF *conf)
0f113f3e
MC
438{
439 char *p;
440 STACK_OF(CONF_VALUE) *sktmp;
441 CONF_VALUE *cnf;
442 int i;
75ebbd9a
RS
443
444 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
0f113f3e
MC
445 ERR_clear_error();
446 return 1;
447 }
75ebbd9a 448 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
7e1b7485 449 BIO_printf(bio_err, "problem loading oid section %s\n", p);
0f113f3e
MC
450 return 0;
451 }
452 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
453 cnf = sk_CONF_VALUE_value(sktmp, i);
454 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
7e1b7485 455 BIO_printf(bio_err, "problem creating object %s=%s\n",
0f113f3e
MC
456 cnf->name, cnf->value);
457 return 0;
458 }
459 }
460 return 1;
431b0cce
RL
461}
462
ae89578b
SL
463CONF *app_load_config_modules(const char *configfile)
464{
465 CONF *conf = NULL;
466
467 if (configfile != NULL) {
15795943 468 if ((conf = app_load_config_verbose(configfile, 1)) == NULL)
ae89578b
SL
469 return NULL;
470 if (configfile != default_config_file && !app_load_modules(conf)) {
471 NCONF_free(conf);
472 conf = NULL;
473 }
474 }
475 return conf;
476}
477
400e2acf
DDO
478#define IS_HTTP(uri) ((uri) != NULL \
479 && strncmp(uri, OSSL_HTTP_PREFIX, strlen(OSSL_HTTP_PREFIX)) == 0)
480#define IS_HTTPS(uri) ((uri) != NULL \
481 && strncmp(uri, OSSL_HTTPS_PREFIX, strlen(OSSL_HTTPS_PREFIX)) == 0)
9498dac4 482
d382e796 483X509 *load_cert_pass(const char *uri, int format, int maybe_stdin,
6d382c74 484 const char *pass, const char *desc)
0f113f3e 485{
6d382c74 486 X509 *cert = NULL;
0f113f3e 487
6d382c74
DDO
488 if (desc == NULL)
489 desc = "certificate";
9498dac4
DDO
490 if (IS_HTTPS(uri))
491 BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
492 else if (IS_HTTP(uri))
493 cert = X509_load_http(uri, NULL, NULL, 0 /* timeout */);
494 else
d382e796 495 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
9498dac4 496 NULL, NULL, NULL, &cert, NULL, NULL, NULL);
6d382c74 497 if (cert == NULL) {
01c12100 498 BIO_printf(bio_err, "Unable to load %s\n", desc);
7e1b7485 499 ERR_print_errors(bio_err);
0f113f3e 500 }
6d382c74 501 return cert;
0f113f3e 502}
90ae4673 503
d382e796
TM
504X509_CRL *load_crl(const char *uri, int format, int maybe_stdin,
505 const char *desc)
6d382c74
DDO
506{
507 X509_CRL *crl = NULL;
9d5aca65 508
6d382c74
DDO
509 if (desc == NULL)
510 desc = "CRL";
9498dac4
DDO
511 if (IS_HTTPS(uri))
512 BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
513 else if (IS_HTTP(uri))
514 crl = X509_CRL_load_http(uri, NULL, NULL, 0 /* timeout */);
515 else
d382e796 516 (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
9498dac4 517 NULL, NULL, NULL, NULL, NULL, &crl, NULL);
6d382c74 518 if (crl == NULL) {
01c12100 519 BIO_printf(bio_err, "Unable to load %s\n", desc);
0f113f3e 520 ERR_print_errors(bio_err);
0f113f3e 521 }
6d382c74 522 return crl;
9d5aca65
DO
523}
524
525X509_REQ *load_csr(const char *file, int format, const char *desc)
526{
527 X509_REQ *req = NULL;
528 BIO *in;
529
d382e796
TM
530 if (format == FORMAT_UNDEF)
531 format = FORMAT_PEM;
6d382c74
DDO
532 if (desc == NULL)
533 desc = "CSR";
9d5aca65
DO
534 in = bio_open_default(file, 'r', format);
535 if (in == NULL)
536 goto end;
537
538 if (format == FORMAT_ASN1)
539 req = d2i_X509_REQ_bio(in, NULL);
540 else if (format == FORMAT_PEM)
541 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
3ee4e8ce 542 else
51c833ac 543 print_format_error(format, OPT_FMT_PEMDER);
fdb78f3d 544
0f113f3e 545 end:
6d382c74 546 if (req == NULL) {
01c12100 547 BIO_printf(bio_err, "Unable to load %s\n", desc);
9d5aca65
DO
548 ERR_print_errors(bio_err);
549 }
0f113f3e 550 BIO_free(in);
9d5aca65 551 return req;
0f113f3e 552}
fdb78f3d 553
6d382c74
DDO
554void cleanse(char *str)
555{
556 if (str != NULL)
557 OPENSSL_cleanse(str, strlen(str));
558}
559
560void clear_free(char *str)
561{
562 if (str != NULL)
563 OPENSSL_clear_free(str, strlen(str));
564}
565
566EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
9d5aca65 567 const char *pass, ENGINE *e, const char *desc)
0f113f3e 568{
0f113f3e 569 EVP_PKEY *pkey = NULL;
f91d003a 570 char *allocated_uri = NULL;
0f113f3e 571
6d382c74
DDO
572 if (desc == NULL)
573 desc = "private key";
0f113f3e 574
0f113f3e 575 if (format == FORMAT_ENGINE) {
f91d003a 576 uri = allocated_uri = make_engine_uri(e, uri, desc);
0f113f3e 577 }
d382e796 578 (void)load_key_certs_crls(uri, format, may_stdin, pass, desc,
f91d003a 579 &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
3ee4e8ce 580
f91d003a 581 OPENSSL_free(allocated_uri);
26a7d938 582 return pkey;
0f113f3e 583}
90ae4673 584
6d382c74 585EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
9d5aca65 586 const char *pass, ENGINE *e, const char *desc)
0f113f3e 587{
0f113f3e 588 EVP_PKEY *pkey = NULL;
f91d003a 589 char *allocated_uri = NULL;
0f113f3e 590
6d382c74
DDO
591 if (desc == NULL)
592 desc = "public key";
0f113f3e 593
0f113f3e 594 if (format == FORMAT_ENGINE) {
f91d003a 595 uri = allocated_uri = make_engine_uri(e, uri, desc);
2234212c 596 }
d382e796 597 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
f91d003a 598 NULL, &pkey, NULL, NULL, NULL, NULL, NULL);
2c90e80d 599
f91d003a 600 OPENSSL_free(allocated_uri);
26a7d938 601 return pkey;
0f113f3e 602}
bd08a2bd 603
d382e796
TM
604EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin,
605 const char *keytype, const char *desc)
b78c777e
RL
606{
607 EVP_PKEY *params = NULL;
608
609 if (desc == NULL)
610 desc = "key parameters";
611
d382e796 612 (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
b78c777e 613 NULL, NULL, &params, NULL, NULL, NULL, NULL);
8b0ec099
MC
614 if (params != NULL && keytype != NULL && !EVP_PKEY_is_a(params, keytype)) {
615 BIO_printf(bio_err,
616 "Unable to load %s from %s (unexpected parameters type)\n",
617 desc, uri);
b78c777e 618 ERR_print_errors(bio_err);
8b0ec099
MC
619 EVP_PKEY_free(params);
620 params = NULL;
b78c777e
RL
621 }
622 return params;
623}
624
e306f83c
RL
625void app_bail_out(char *fmt, ...)
626{
627 va_list args;
628
629 va_start(args, fmt);
630 BIO_vprintf(bio_err, fmt, args);
631 va_end(args);
632 ERR_print_errors(bio_err);
a7e4ca5b 633 exit(EXIT_FAILURE);
e306f83c
RL
634}
635
b1c908f4 636void *app_malloc(size_t sz, const char *what)
68dc6824
RS
637{
638 void *vp = OPENSSL_malloc(sz);
639
e306f83c 640 if (vp == NULL)
b1c908f4 641 app_bail_out("%s: Could not allocate %zu bytes for %s\n",
e306f83c 642 opt_getprog(), sz, what);
68dc6824
RS
643 return vp;
644}
645
f62846b7
DDO
646char *next_item(char *opt) /* in list separated by comma and/or space */
647{
648 /* advance to separator (comma or whitespace), if any */
db89d8f0 649 while (*opt != ',' && !isspace(*opt) && *opt != '\0')
f62846b7 650 opt++;
f62846b7
DDO
651 if (*opt != '\0') {
652 /* terminate current item */
653 *opt++ = '\0';
654 /* skip over any whitespace after separator */
655 while (isspace(*opt))
656 opt++;
657 }
658 return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
659}
660
661static void warn_cert_msg(const char *uri, X509 *cert, const char *msg)
662{
663 char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
664
49f07be4 665 BIO_printf(bio_err, "Warning: certificate from '%s' with subject '%s' %s\n",
f62846b7
DDO
666 uri, subj, msg);
667 OPENSSL_free(subj);
668}
669
670static void warn_cert(const char *uri, X509 *cert, int warn_EE,
671 X509_VERIFY_PARAM *vpm)
672{
673 uint32_t ex_flags = X509_get_extension_flags(cert);
674 int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
675 X509_get0_notAfter(cert));
676
677 if (res != 0)
678 warn_cert_msg(uri, cert, res > 0 ? "has expired" : "not yet valid");
679 if (warn_EE && (ex_flags & EXFLAG_V1) == 0 && (ex_flags & EXFLAG_CA) == 0)
680 warn_cert_msg(uri, cert, "is not a CA cert");
681}
682
683static void warn_certs(const char *uri, STACK_OF(X509) *certs, int warn_EE,
684 X509_VERIFY_PARAM *vpm)
685{
686 int i;
687
688 for (i = 0; i < sk_X509_num(certs); i++)
689 warn_cert(uri, sk_X509_value(certs, i), warn_EE, vpm);
690}
691
692int load_cert_certs(const char *uri,
693 X509 **pcert, STACK_OF(X509) **pcerts,
694 int exclude_http, const char *pass, const char *desc,
695 X509_VERIFY_PARAM *vpm)
696{
697 int ret = 0;
698 char *pass_string;
699
700 if (exclude_http && (strncasecmp(uri, "http://", 7) == 0
701 || strncasecmp(uri, "https://", 8) == 0)) {
702 BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
703 return ret;
704 }
705 pass_string = get_passwd(pass, desc);
d382e796
TM
706 ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass_string, desc,
707 NULL, NULL, NULL,
f62846b7
DDO
708 pcert, pcerts, NULL, NULL);
709 clear_free(pass_string);
710
711 if (ret) {
712 if (pcert != NULL)
713 warn_cert(uri, *pcert, 0, vpm);
714 warn_certs(uri, *pcerts, 1, vpm);
715 } else {
716 sk_X509_pop_free(*pcerts, X509_free);
717 *pcerts = NULL;
718 }
719 return ret;
720}
721
722STACK_OF(X509) *load_certs_multifile(char *files, const char *pass,
723 const char *desc, X509_VERIFY_PARAM *vpm)
724{
725 STACK_OF(X509) *certs = NULL;
726 STACK_OF(X509) *result = sk_X509_new_null();
727
728 if (files == NULL)
729 goto err;
730 if (result == NULL)
731 goto oom;
732
733 while (files != NULL) {
734 char *next = next_item(files);
735
736 if (!load_cert_certs(files, NULL, &certs, 0, pass, desc, vpm))
737 goto err;
738 if (!X509_add_certs(result, certs,
739 X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
740 goto oom;
741 sk_X509_pop_free(certs, X509_free);
742 certs = NULL;
743 files = next;
744 }
745 return result;
746
747 oom:
748 BIO_printf(bio_err, "out of memory\n");
749 err:
750 sk_X509_pop_free(certs, X509_free);
751 sk_X509_pop_free(result, X509_free);
752 return NULL;
753}
754
755static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
756 const STACK_OF(X509) *certs /* may NULL */)
757{
758 int i;
759
760 if (store == NULL)
761 store = X509_STORE_new();
762 if (store == NULL)
763 return NULL;
764 for (i = 0; i < sk_X509_num(certs); i++) {
765 if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
766 X509_STORE_free(store);
767 return NULL;
768 }
769 }
770 return store;
771}
772
773/*
774 * Create cert store structure with certificates read from given file(s).
775 * Returns pointer to created X509_STORE on success, NULL on error.
776 */
777X509_STORE *load_certstore(char *input, const char *pass, const char *desc,
778 X509_VERIFY_PARAM *vpm)
779{
780 X509_STORE *store = NULL;
781 STACK_OF(X509) *certs = NULL;
782
783 while (input != NULL) {
784 char *next = next_item(input);
785 int ok;
786
787 if (!load_cert_certs(input, NULL, &certs, 1, pass, desc, vpm)) {
788 X509_STORE_free(store);
789 return NULL;
790 }
791 ok = (store = sk_X509_to_store(store, certs)) != NULL;
792 sk_X509_pop_free(certs, X509_free);
793 certs = NULL;
794 if (!ok)
795 return NULL;
796 input = next;
797 }
798 return store;
799}
800
0996dc54 801/*
6b4a77f5 802 * Initialize or extend, if *certs != NULL, a certificate stack.
c4adc5ba 803 * The caller is responsible for freeing *certs if its value is left not NULL.
0996dc54 804 */
ea51096e 805int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs,
a773b52a 806 const char *pass, const char *desc)
0f113f3e 807{
c4adc5ba 808 int was_NULL = *certs == NULL;
d382e796
TM
809 int ret = load_key_certs_crls(uri, FORMAT_UNDEF, maybe_stdin,
810 pass, desc, NULL, NULL,
ea51096e 811 NULL, NULL, certs, NULL, NULL);
c4adc5ba
DDO
812
813 if (!ret && was_NULL) {
814 sk_X509_pop_free(*certs, X509_free);
815 *certs = NULL;
816 }
817 return ret;
0f113f3e 818}
245d2ee3 819
0996dc54 820/*
6b4a77f5 821 * Initialize or extend, if *crls != NULL, a certificate stack.
c4adc5ba 822 * The caller is responsible for freeing *crls if its value is left not NULL.
0996dc54 823 */
b3c5aadf 824int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
a773b52a 825 const char *pass, const char *desc)
0f113f3e 826{
c4adc5ba 827 int was_NULL = *crls == NULL;
d382e796
TM
828 int ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass, desc,
829 NULL, NULL, NULL,
c4adc5ba
DDO
830 NULL, NULL, NULL, crls);
831
832 if (!ret && was_NULL) {
833 sk_X509_CRL_pop_free(*crls, X509_CRL_free);
834 *crls = NULL;
835 }
836 return ret;
0f113f3e
MC
837}
838
d382e796
TM
839static const char *format2string(int format)
840{
841 switch(format) {
842 case FORMAT_PEM:
843 return "PEM";
844 case FORMAT_ASN1:
845 return "DER";
846 }
847 return NULL;
848}
849
6c3d101a 850/* Set type expectation, but clear it if objects of different types expected. */
466cab47 851#define SET_EXPECT(expect, val) ((expect) = (expect) < 0 ? (val) : ((expect) == (val) ? (val) : 0))
6d382c74
DDO
852/*
853 * Load those types of credentials for which the result pointer is not NULL.
854 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
b3c5aadf
DDO
855 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
856 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
857 * If pcerts is non-NULL then all available certificates are appended to *pcerts
858 * except any certificate assigned to *pcert.
859 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
860 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
861 * except any CRL assigned to *pcrl.
862 * In any case (also on error) the caller is responsible for freeing all members
863 * of *pcerts and *pcrls (as far as they are not NULL).
6d382c74 864 */
d382e796 865int load_key_certs_crls(const char *uri, int format, int maybe_stdin,
b3c5aadf
DDO
866 const char *pass, const char *desc,
867 EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
b78c777e 868 EVP_PKEY **pparams,
b3c5aadf
DDO
869 X509 **pcert, STACK_OF(X509) **pcerts,
870 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
6d382c74
DDO
871{
872 PW_CB_DATA uidata;
873 OSSL_STORE_CTX *ctx = NULL;
b4250010 874 OSSL_LIB_CTX *libctx = app_get0_libctx();
6725682d 875 const char *propq = app_get0_propq();
b3c5aadf
DDO
876 int ncerts = 0;
877 int ncrls = 0;
50eb2a50
DDO
878 const char *failed =
879 ppkey != NULL ? "key" : ppubkey != NULL ? "public key" :
8b0ec099
MC
880 pparams != NULL ? "params" : pcert != NULL ? "cert" :
881 pcrl != NULL ? "CRL" : pcerts != NULL ? "certs" :
882 pcrls != NULL ? "CRLs" : NULL;
f91d003a 883 int cnt_expectations = 0;
6c3d101a 884 int expect = -1;
d382e796
TM
885 const char *input_type;
886 OSSL_PARAM itp[2];
887 const OSSL_PARAM *params = NULL;
6d382c74 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;
6c9515b7
DDO
2260 }
2261
2262 if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0)
2263 rv = (X509_sign_ctx(cert, mctx) > 0);
2264 end:
2265 EVP_MD_CTX_free(mctx);
2266 return rv;
2267}
2268
2269/* Sign the certificate request info */
91034b68 2270int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md,
6c9515b7
DDO
2271 STACK_OF(OPENSSL_STRING) *sigopts)
2272{
2273 int rv = 0;
2274 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2275
2276 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2277 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
2278 EVP_MD_CTX_free(mctx);
2279 return rv;
2280}
2281
2282/* Sign the CRL info */
91034b68 2283int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md,
6c9515b7
DDO
2284 STACK_OF(OPENSSL_STRING) *sigopts)
2285{
2286 int rv = 0;
2287 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2288
2289 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2290 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
2291 EVP_MD_CTX_free(mctx);
2292 return rv;
2293}
2294
2295int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
2296{
2297 int rv = 0;
2298
2299 if (do_x509_init(x, vfyopts) > 0)
2300 rv = (X509_verify(x, pkey) > 0);
2301 return rv;
2302}
2303
2304int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
2305 STACK_OF(OPENSSL_STRING) *vfyopts)
2306{
2307 int rv = 0;
2308
2309 if (do_x509_req_init(x, vfyopts) > 0)
a0baa98b
PG
2310 rv = (X509_REQ_verify_ex(x, pkey,
2311 app_get0_libctx(), app_get0_propq()) > 0);
6c9515b7
DDO
2312 return rv;
2313}
2314
0090a686
DSH
2315/* Get first http URL from a DIST_POINT structure */
2316
2317static const char *get_dp_url(DIST_POINT *dp)
0f113f3e
MC
2318{
2319 GENERAL_NAMES *gens;
2320 GENERAL_NAME *gen;
2321 int i, gtype;
2322 ASN1_STRING *uri;
2323 if (!dp->distpoint || dp->distpoint->type != 0)
2324 return NULL;
2325 gens = dp->distpoint->name.fullname;
2326 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2327 gen = sk_GENERAL_NAME_value(gens, i);
2328 uri = GENERAL_NAME_get0_value(gen, &gtype);
2329 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
17ebf85a 2330 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
9498dac4
DDO
2331
2332 if (IS_HTTP(uptr)) /* can/should not use HTTPS here */
0f113f3e
MC
2333 return uptr;
2334 }
2335 }
2336 return NULL;
2337}
2338
2339/*
2340 * Look through a CRLDP structure and attempt to find an http URL to
2341 * downloads a CRL from.
0090a686
DSH
2342 */
2343
2344static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
0f113f3e
MC
2345{
2346 int i;
2347 const char *urlptr = NULL;
2348 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2349 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2350 urlptr = get_dp_url(dp);
e9d62da6 2351 if (urlptr != NULL)
d382e796 2352 return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP");
0f113f3e
MC
2353 }
2354 return NULL;
2355}
2356
2357/*
0aa87e86
DDO
2358 * Example of downloading CRLs from CRLDP:
2359 * not usable for real world as it always downloads and doesn't cache anything.
0090a686
DSH
2360 */
2361
8cc86b81
DDO
2362static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
2363 const X509_NAME *nm)
0f113f3e
MC
2364{
2365 X509 *x;
2366 STACK_OF(X509_CRL) *crls = NULL;
2367 X509_CRL *crl;
2368 STACK_OF(DIST_POINT) *crldp;
7e1b7485
RS
2369
2370 crls = sk_X509_CRL_new_null();
2371 if (!crls)
2372 return NULL;
0f113f3e
MC
2373 x = X509_STORE_CTX_get_current_cert(ctx);
2374 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2375 crl = load_crl_crldp(crldp);
2376 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
fe2b7dfd
MC
2377 if (!crl) {
2378 sk_X509_CRL_free(crls);
0f113f3e 2379 return NULL;
fe2b7dfd 2380 }
0f113f3e
MC
2381 sk_X509_CRL_push(crls, crl);
2382 /* Try to download delta CRL */
2383 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2384 crl = load_crl_crldp(crldp);
2385 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2386 if (crl)
2387 sk_X509_CRL_push(crls, crl);
2388 return crls;
2389}
0090a686
DSH
2390
2391void store_setup_crl_download(X509_STORE *st)
0f113f3e
MC
2392{
2393 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2394}
0090a686 2395
29f178bd
DDO
2396#ifndef OPENSSL_NO_SOCK
2397static const char *tls_error_hint(void)
2398{
2399 unsigned long err = ERR_peek_error();
2400
2401 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2402 err = ERR_peek_last_error();
2403 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2404 return NULL;
2405
2406 switch (ERR_GET_REASON(err)) {
2407 case SSL_R_WRONG_VERSION_NUMBER:
2408 return "The server does not support (a suitable version of) TLS";
2409 case SSL_R_UNKNOWN_PROTOCOL:
2410 return "The server does not support HTTPS";
2411 case SSL_R_CERTIFICATE_VERIFY_FAILED:
2412 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2413 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
2414 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2415 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
2416 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2417 default: /* no error or no hint available for error */
2418 return NULL;
2419 }
2420}
2421
2422/* HTTP callback function that supports TLS connection also via HTTPS proxy */
2423BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
2424{
29f178bd 2425 if (connect && detail) { /* connecting with TLS */
ef203432
DDO
2426 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
2427 SSL_CTX *ssl_ctx = info->ssl_ctx;
2428 SSL *ssl;
2429 BIO *sbio = NULL;
2430
29f178bd
DDO
2431 if ((info->use_proxy
2432 && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
2433 NULL, NULL, /* no proxy credentials */
2434 info->timeout, bio_err, opt_getprog()))
2435 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2436 return NULL;
2437 }
2438 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
2439 BIO_free(sbio);
2440 return NULL;
2441 }
2442
2443 SSL_set_tlsext_host_name(ssl, info->server);
2444
2445 SSL_set_connect_state(ssl);
2446 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2447
2448 hbio = BIO_push(sbio, hbio);
2449 } else if (!connect && !detail) { /* disconnecting after error */
2450 const char *hint = tls_error_hint();
ef203432 2451
29f178bd 2452 if (hint != NULL)
afe554c2 2453 ERR_add_error_data(2, " : ", hint);
29f178bd
DDO
2454 /*
2455 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2456 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2457 */
2458 }
2459 return hbio;
2460}
2461
ef203432
DDO
2462void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info)
2463{
2464 if (info != NULL) {
2465 SSL_CTX_free(info->ssl_ctx);
2466 OPENSSL_free(info);
2467 }
2468}
2469
29f178bd 2470ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
afe554c2 2471 const char *no_proxy, SSL_CTX *ssl_ctx,
29f178bd
DDO
2472 const STACK_OF(CONF_VALUE) *headers,
2473 long timeout, const char *expected_content_type,
2474 const ASN1_ITEM *it)
2475{
2476 APP_HTTP_TLS_INFO info;
2477 char *server;
2478 char *port;
2479 int use_ssl;
8f965908 2480 BIO *mem;
29f178bd
DDO
2481 ASN1_VALUE *resp = NULL;
2482
2483 if (url == NULL || it == NULL) {
9311d0c4 2484 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
29f178bd
DDO
2485 return NULL;
2486 }
2487
7932982b
DDO
2488 if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL /* userinfo */, &server, &port,
2489 NULL /* port_num, */, NULL, NULL, NULL))
29f178bd
DDO
2490 return NULL;
2491 if (use_ssl && ssl_ctx == NULL) {
a150f8e1
RL
2492 ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER,
2493 "missing SSL_CTX");
29f178bd
DDO
2494 goto end;
2495 }
2496
2497 info.server = server;
2498 info.port = port;
2499 info.use_proxy = proxy != NULL;
2500 info.timeout = timeout;
2501 info.ssl_ctx = ssl_ctx;
8f965908
DDO
2502 mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2503 app_http_tls_cb, &info, 0 /* buf_size */, headers,
2504 expected_content_type, 1 /* expect_asn1 */,
647a5dbf 2505 OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout);
8f965908
DDO
2506 resp = ASN1_item_d2i_bio(it, mem, NULL);
2507 BIO_free(mem);
2508
29f178bd
DDO
2509 end:
2510 OPENSSL_free(server);
2511 OPENSSL_free(port);
2512 return resp;
2513
2514}
2515
2516ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2517 const char *path, const char *proxy,
afe554c2 2518 const char *no_proxy, SSL_CTX *ssl_ctx,
29f178bd
DDO
2519 const STACK_OF(CONF_VALUE) *headers,
2520 const char *content_type,
2521 ASN1_VALUE *req, const ASN1_ITEM *req_it,
82990287 2522 const char *expected_content_type,
29f178bd
DDO
2523 long timeout, const ASN1_ITEM *rsp_it)
2524{
2525 APP_HTTP_TLS_INFO info;
8f965908
DDO
2526 BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req);
2527 ASN1_VALUE *res;
29f178bd 2528
8f965908
DDO
2529 if (req_mem == NULL)
2530 return NULL;
29f178bd
DDO
2531 info.server = host;
2532 info.port = port;
2533 info.use_proxy = proxy != NULL;
2534 info.timeout = timeout;
2535 info.ssl_ctx = ssl_ctx;
8f965908
DDO
2536 rsp = OSSL_HTTP_transfer(NULL, host, port, path, ssl_ctx != NULL,
2537 proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2538 app_http_tls_cb, &info,
2539 0 /* buf_size */, headers, content_type, req_mem,
82990287 2540 expected_content_type, 1 /* expect_asn1 */,
647a5dbf 2541 OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout,
8f965908
DDO
2542 0 /* keep_alive */);
2543 BIO_free(req_mem);
2544 res = ASN1_item_d2i_bio(rsp_it, rsp, NULL);
2545 BIO_free(rsp);
2546 return res;
29f178bd
DDO
2547}
2548
2549#endif
2550
0a39d8f2
AP
2551/*
2552 * Platform-specific sections
2553 */
ffa10187 2554#if defined(_WIN32)
a1ad253f
AP
2555# ifdef fileno
2556# undef fileno
2557# define fileno(a) (int)_fileno(a)
2558# endif
2559
2560# include <windows.h>
2561# include <tchar.h>
2562
2563static int WIN32_rename(const char *from, const char *to)
0f113f3e
MC
2564{
2565 TCHAR *tfrom = NULL, *tto;
2566 DWORD err;
2567 int ret = 0;
2568
2569 if (sizeof(TCHAR) == 1) {
2570 tfrom = (TCHAR *)from;
2571 tto = (TCHAR *)to;
2572 } else { /* UNICODE path */
2573
2574 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
b1ad95e3 2575 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
0f113f3e
MC
2576 if (tfrom == NULL)
2577 goto err;
2578 tto = tfrom + flen;
2579# if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2580 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2581# endif
2582 for (i = 0; i < flen; i++)
2583 tfrom[i] = (TCHAR)from[i];
2584# if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2585 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2586# endif
2587 for (i = 0; i < tlen; i++)
2588 tto[i] = (TCHAR)to[i];
2589 }
2590
2591 if (MoveFile(tfrom, tto))
2592 goto ok;
2593 err = GetLastError();
2594 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2595 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2596 goto ok;
2597 err = GetLastError();
2598 }
2599 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2600 errno = ENOENT;
2601 else if (err == ERROR_ACCESS_DENIED)
2602 errno = EACCES;
2603 else
2604 errno = EINVAL; /* we could map more codes... */
2605 err:
2606 ret = -1;
2607 ok:
2608 if (tfrom != NULL && tfrom != (TCHAR *)from)
2609 free(tfrom);
2610 return ret;
2611}
0a39d8f2
AP
2612#endif
2613
2614/* app_tminterval section */
2615#if defined(_WIN32)
0f113f3e
MC
2616double app_tminterval(int stop, int usertime)
2617{
2618 FILETIME now;
2619 double ret = 0;
2620 static ULARGE_INTEGER tmstart;
2621 static int warning = 1;
2622# ifdef _WIN32_WINNT
2623 static HANDLE proc = NULL;
2624
2625 if (proc == NULL) {
2626 if (check_winnt())
2627 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2628 GetCurrentProcessId());
2629 if (proc == NULL)
2630 proc = (HANDLE) - 1;
2631 }
2632
2633 if (usertime && proc != (HANDLE) - 1) {
2634 FILETIME junk;
2635 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2636 } else
2637# endif
2638 {
2639 SYSTEMTIME systime;
9135fddb 2640
0f113f3e
MC
2641 if (usertime && warning) {
2642 BIO_printf(bio_err, "To get meaningful results, run "
2643 "this program on idle system.\n");
2644 warning = 0;
2645 }
2646 GetSystemTime(&systime);
2647 SystemTimeToFileTime(&systime, &now);
2648 }
9135fddb 2649
0f113f3e
MC
2650 if (stop == TM_START) {
2651 tmstart.u.LowPart = now.dwLowDateTime;
2652 tmstart.u.HighPart = now.dwHighDateTime;
2653 } else {
2654 ULARGE_INTEGER tmstop;
9135fddb 2655
0f113f3e
MC
2656 tmstop.u.LowPart = now.dwLowDateTime;
2657 tmstop.u.HighPart = now.dwHighDateTime;
9135fddb 2658
0f113f3e
MC
2659 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2660 }
9135fddb 2661
26a7d938 2662 return ret;
0f113f3e 2663}
5c8b7b4c 2664#elif defined(OPENSSL_SYS_VXWORKS)
0f113f3e 2665# include <time.h>
0a39d8f2 2666
0f113f3e
MC
2667double app_tminterval(int stop, int usertime)
2668{
2669 double ret = 0;
2670# ifdef CLOCK_REALTIME
2671 static struct timespec tmstart;
2672 struct timespec now;
2673# else
2674 static unsigned long tmstart;
2675 unsigned long now;
2676# endif
2677 static int warning = 1;
2678
2679 if (usertime && warning) {
2680 BIO_printf(bio_err, "To get meaningful results, run "
2681 "this program on idle system.\n");
2682 warning = 0;
2683 }
2684# ifdef CLOCK_REALTIME
2685 clock_gettime(CLOCK_REALTIME, &now);
2686 if (stop == TM_START)
2687 tmstart = now;
2688 else
2689 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2690 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2691# else
2692 now = tickGet();
2693 if (stop == TM_START)
2694 tmstart = now;
2695 else
2696 ret = (now - tmstart) / (double)sysClkRateGet();
2697# endif
26a7d938 2698 return ret;
0f113f3e 2699}
0a39d8f2 2700
0f113f3e
MC
2701#elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2702# include <sys/times.h>
0a39d8f2 2703
0f113f3e
MC
2704double app_tminterval(int stop, int usertime)
2705{
2706 double ret = 0;
db71d315 2707 struct tms rus;
2bd928a1
TM
2708 clock_t now = times(&rus);
2709 static clock_t tmstart;
0f113f3e
MC
2710
2711 if (usertime)
2712 now = rus.tms_utime;
2713
2234212c 2714 if (stop == TM_START) {
0f113f3e 2715 tmstart = now;
2234212c 2716 } else {
2bd928a1 2717 long int tck = sysconf(_SC_CLK_TCK);
0f113f3e
MC
2718 ret = (now - tmstart) / (double)tck;
2719 }
2720
26a7d938 2721 return ret;
0f113f3e 2722}
0a39d8f2 2723
0f113f3e
MC
2724#else
2725# include <sys/time.h>
2726# include <sys/resource.h>
0a39d8f2 2727
0f113f3e
MC
2728double app_tminterval(int stop, int usertime)
2729{
2730 double ret = 0;
2731 struct rusage rus;
2732 struct timeval now;
2733 static struct timeval tmstart;
2734
2735 if (usertime)
2736 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2737 else
2738 gettimeofday(&now, NULL);
2739
2740 if (stop == TM_START)
2741 tmstart = now;
2742 else
2743 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2744 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2745
2746 return ret;
2747}
0a39d8f2 2748#endif
a1ad253f 2749
7e1b7485
RS
2750int app_access(const char* name, int flag)
2751{
2752#ifdef _WIN32
2753 return _access(name, flag);
2754#else
2755 return access(name, flag);
2756#endif
2757}
2758
ffa10187 2759int app_isdir(const char *name)
0f113f3e 2760{
a43ce58f 2761 return opt_isdir(name);
0f113f3e 2762}
ffa10187 2763
0a39d8f2 2764/* raw_read|write section */
51e5133d
RL
2765#if defined(__VMS)
2766# include "vms_term_sock.h"
2767static int stdin_sock = -1;
2768
2769static void close_stdin_sock(void)
2770{
2771 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2772}
2773
2774int fileno_stdin(void)
2775{
2776 if (stdin_sock == -1) {
2777 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2778 atexit(close_stdin_sock);
2779 }
2780
2781 return stdin_sock;
2782}
2783#else
2784int fileno_stdin(void)
2785{
2786 return fileno(stdin);
2787}
2788#endif
2789
2790int fileno_stdout(void)
2791{
2792 return fileno(stdout);
2793}
2794
ffa10187 2795#if defined(_WIN32) && defined(STD_INPUT_HANDLE)
0f113f3e
MC
2796int raw_read_stdin(void *buf, int siz)
2797{
2798 DWORD n;
2799 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
26a7d938 2800 return n;
0f113f3e 2801 else
26a7d938 2802 return -1;
0f113f3e 2803}
51e5133d 2804#elif defined(__VMS)
2234212c 2805# include <sys/socket.h>
a19228b7 2806
51e5133d
RL
2807int raw_read_stdin(void *buf, int siz)
2808{
2809 return recv(fileno_stdin(), buf, siz, 0);
2810}
ffa10187 2811#else
08073700
RB
2812# if defined(__TANDEM)
2813# if defined(OPENSSL_TANDEM_FLOSS)
2814# include <floss.h(floss_read)>
2815# endif
2816# endif
0f113f3e
MC
2817int raw_read_stdin(void *buf, int siz)
2818{
51e5133d 2819 return read(fileno_stdin(), buf, siz);
0f113f3e 2820}
ffa10187
AP
2821#endif
2822
2823#if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
0f113f3e
MC
2824int raw_write_stdout(const void *buf, int siz)
2825{
2826 DWORD n;
2827 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
26a7d938 2828 return n;
0f113f3e 2829 else
26a7d938 2830 return -1;
0f113f3e 2831}
cdb5129e 2832#elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
08073700
RB
2833# if defined(__TANDEM)
2834# if defined(OPENSSL_TANDEM_FLOSS)
2835# include <floss.h(floss_write)>
2836# endif
2837# endif
2838int raw_write_stdout(const void *buf,int siz)
2839{
2840 return write(fileno(stdout),(void*)buf,siz);
2841}
ffa10187 2842#else
08073700
RB
2843# if defined(__TANDEM)
2844# if defined(OPENSSL_TANDEM_FLOSS)
2845# include <floss.h(floss_write)>
2846# endif
2847# endif
0f113f3e
MC
2848int raw_write_stdout(const void *buf, int siz)
2849{
51e5133d 2850 return write(fileno_stdout(), buf, siz);
0f113f3e 2851}
ffa10187 2852#endif
a412b891
RL
2853
2854/*
a43ce58f 2855 * Centralized handling of input and output files with format specification
a412b891
RL
2856 * The format is meant to show what the input and output is supposed to be,
2857 * and is therefore a show of intent more than anything else. However, it
a43ce58f 2858 * does impact behavior on some platforms, such as differentiating between
a412b891
RL
2859 * text and binary input/output on non-Unix platforms
2860 */
a60994df 2861BIO *dup_bio_in(int format)
a412b891 2862{
a60994df 2863 return BIO_new_fp(stdin,
a43ce58f 2864 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
a60994df
RL
2865}
2866
2867BIO *dup_bio_out(int format)
2868{
2869 BIO *b = BIO_new_fp(stdout,
a43ce58f 2870 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
71bb86f0
RL
2871 void *prefix = NULL;
2872
a412b891 2873#ifdef OPENSSL_SYS_VMS
a43ce58f 2874 if (FMT_istext(format))
a60994df 2875 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
149bd5d6 2876#endif
71bb86f0 2877
682b444f
RL
2878 if (FMT_istext(format)
2879 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
e79ae962
RL
2880 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2881 BIO_set_prefix(b, prefix);
71bb86f0
RL
2882 }
2883
149bd5d6
RL
2884 return b;
2885}
2886
2887BIO *dup_bio_err(int format)
2888{
2889 BIO *b = BIO_new_fp(stderr,
a43ce58f 2890 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
149bd5d6 2891#ifdef OPENSSL_SYS_VMS
a43ce58f 2892 if (FMT_istext(format))
149bd5d6 2893 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
a412b891
RL
2894#endif
2895 return b;
2896}
2897
2898void unbuffer(FILE *fp)
2899{
90dbd250
RL
2900/*
2901 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2902 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2903 * However, we trust that the C RTL will never give us a FILE pointer
2904 * above the first 4 GB of memory, so we simply turn off the warning
2905 * temporarily.
2906 */
2907#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2908# pragma environment save
2909# pragma message disable maylosedata2
2910#endif
a412b891 2911 setbuf(fp, NULL);
90dbd250
RL
2912#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2913# pragma environment restore
2914#endif
a412b891
RL
2915}
2916
2917static const char *modestr(char mode, int format)
2918{
2919 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2920
2921 switch (mode) {
2922 case 'a':
a43ce58f 2923 return FMT_istext(format) ? "a" : "ab";
a412b891 2924 case 'r':
a43ce58f 2925 return FMT_istext(format) ? "r" : "rb";
a412b891 2926 case 'w':
a43ce58f 2927 return FMT_istext(format) ? "w" : "wb";
a412b891
RL
2928 }
2929 /* The assert above should make sure we never reach this point */
2930 return NULL;
2931}
2932
2933static const char *modeverb(char mode)
2934{
2935 switch (mode) {
2936 case 'a':
2937 return "appending";
2938 case 'r':
2939 return "reading";
2940 case 'w':
2941 return "writing";
2942 }
2943 return "(doing something)";
2944}
2945
2946/*
2947 * Open a file for writing, owner-read-only.
2948 */
2949BIO *bio_open_owner(const char *filename, int format, int private)
2950{
2951 FILE *fp = NULL;
2952 BIO *b = NULL;
1cd5cc36 2953 int fd = -1, bflags, mode, textmode;
a412b891
RL
2954
2955 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2956 return bio_open_default(filename, 'w', format);
2957
2958 mode = O_WRONLY;
2959#ifdef O_CREAT
2960 mode |= O_CREAT;
2961#endif
2962#ifdef O_TRUNC
2963 mode |= O_TRUNC;
2964#endif
a43ce58f 2965 textmode = FMT_istext(format);
1cd5cc36 2966 if (!textmode) {
a412b891
RL
2967#ifdef O_BINARY
2968 mode |= O_BINARY;
2969#elif defined(_O_BINARY)
2970 mode |= _O_BINARY;
2971#endif
2972 }
2973
fbd03b09
RL
2974#ifdef OPENSSL_SYS_VMS
2975 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
2976 * it still needs to know that we're going binary, or fdopen()
2977 * will fail with "invalid argument"... so we tell VMS what the
2978 * context is.
2979 */
2980 if (!textmode)
2981 fd = open(filename, mode, 0600, "ctx=bin");
2982 else
2983#endif
2984 fd = open(filename, mode, 0600);
a412b891
RL
2985 if (fd < 0)
2986 goto err;
2987 fp = fdopen(fd, modestr('w', format));
2988 if (fp == NULL)
2989 goto err;
2990 bflags = BIO_CLOSE;
1cd5cc36 2991 if (textmode)
a412b891
RL
2992 bflags |= BIO_FP_TEXT;
2993 b = BIO_new_fp(fp, bflags);
2994 if (b)
2995 return b;
2996
2997 err:
2998 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
2999 opt_getprog(), filename, strerror(errno));
3000 ERR_print_errors(bio_err);
3001 /* If we have fp, then fdopen took over fd, so don't close both. */
3002 if (fp)
3003 fclose(fp);
3004 else if (fd >= 0)
3005 close(fd);
3006 return NULL;
3007}
3008
3009static BIO *bio_open_default_(const char *filename, char mode, int format,
3010 int quiet)
3011{
3012 BIO *ret;
3013
3014 if (filename == NULL || strcmp(filename, "-") == 0) {
a60994df 3015 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
a412b891
RL
3016 if (quiet) {
3017 ERR_clear_error();
3018 return ret;
3019 }
3020 if (ret != NULL)
3021 return ret;
3022 BIO_printf(bio_err,
3023 "Can't open %s, %s\n",
3024 mode == 'r' ? "stdin" : "stdout", strerror(errno));
3025 } else {
3026 ret = BIO_new_file(filename, modestr(mode, format));
3027 if (quiet) {
3028 ERR_clear_error();
3029 return ret;
3030 }
3031 if (ret != NULL)
3032 return ret;
3033 BIO_printf(bio_err,
15795943 3034 "Can't open \"%s\" for %s, %s\n",
a412b891
RL
3035 filename, modeverb(mode), strerror(errno));
3036 }
3037 ERR_print_errors(bio_err);
3038 return NULL;
3039}
3040
3041BIO *bio_open_default(const char *filename, char mode, int format)
3042{
3043 return bio_open_default_(filename, mode, format, 0);
3044}
3045
3046BIO *bio_open_default_quiet(const char *filename, char mode, int format)
3047{
3048 return bio_open_default_(filename, mode, format, 1);
3049}
3050
e1b9840e
MC
3051void wait_for_async(SSL *s)
3052{
d6e03b70
MC
3053 /* On Windows select only works for sockets, so we simply don't wait */
3054#ifndef OPENSSL_SYS_WINDOWS
ff75a257 3055 int width = 0;
e1b9840e 3056 fd_set asyncfds;
ff75a257
MC
3057 OSSL_ASYNC_FD *fds;
3058 size_t numfds;
0a345252 3059 size_t i;
e1b9840e 3060
ff75a257
MC
3061 if (!SSL_get_all_async_fds(s, NULL, &numfds))
3062 return;
3063 if (numfds == 0)
e1b9840e 3064 return;
589902b2 3065 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
ff75a257
MC
3066 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
3067 OPENSSL_free(fds);
0a345252 3068 return;
ff75a257 3069 }
e1b9840e 3070
e1b9840e 3071 FD_ZERO(&asyncfds);
0a345252
P
3072 for (i = 0; i < numfds; i++) {
3073 if (width <= (int)fds[i])
3074 width = (int)fds[i] + 1;
3075 openssl_fdset((int)fds[i], &asyncfds);
ff75a257 3076 }
e1b9840e 3077 select(width, (void *)&asyncfds, NULL, NULL, NULL);
0a345252 3078 OPENSSL_free(fds);
d6e03b70 3079#endif
e1b9840e 3080}
75dd6c1a
MC
3081
3082/* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
3083#if defined(OPENSSL_SYS_MSDOS)
3084int has_stdin_waiting(void)
3085{
3086# if defined(OPENSSL_SYS_WINDOWS)
3087 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
3088 DWORD events = 0;
3089 INPUT_RECORD inputrec;
3090 DWORD insize = 1;
3091 BOOL peeked;
3092
3093 if (inhand == INVALID_HANDLE_VALUE) {
3094 return 0;
3095 }
3096
3097 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
3098 if (!peeked) {
3099 /* Probably redirected input? _kbhit() does not work in this case */
3100 if (!feof(stdin)) {
3101 return 1;
3102 }
3103 return 0;
3104 }
3105# endif
3106 return _kbhit();
3107}
3108#endif
17ebf85a
DSH
3109
3110/* Corrupt a signature by modifying final byte */
a0754084 3111void corrupt_signature(const ASN1_STRING *signature)
17ebf85a 3112{
a0754084
DSH
3113 unsigned char *s = signature->data;
3114 s[signature->length - 1] ^= 0x1;
17ebf85a 3115}
dc047d31
DSH
3116
3117int set_cert_times(X509 *x, const char *startdate, const char *enddate,
3118 int days)
3119{
dc047d31 3120 if (startdate == NULL || strcmp(startdate, "today") == 0) {
0b7347ef
DSH
3121 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
3122 return 0;
3123 } else {
04e62715 3124 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
0b7347ef 3125 return 0;
dc047d31 3126 }
dc047d31 3127 if (enddate == NULL) {
0b7347ef
DSH
3128 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
3129 == NULL)
3130 return 0;
04e62715 3131 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
0b7347ef 3132 return 0;
dc047d31 3133 }
0b7347ef 3134 return 1;
dc047d31 3135}
20967afb 3136
64713cb1
CN
3137int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
3138{
3139 int ret = 0;
3140 ASN1_TIME *tm = ASN1_TIME_new();
3141
3142 if (tm == NULL)
3143 goto end;
3144
3145 if (lastupdate == NULL) {
3146 if (X509_gmtime_adj(tm, 0) == NULL)
3147 goto end;
3148 } else {
3149 if (!ASN1_TIME_set_string_X509(tm, lastupdate))
3150 goto end;
3151 }
3152
3153 if (!X509_CRL_set1_lastUpdate(crl, tm))
3154 goto end;
3155
3156 ret = 1;
3157end:
3158 ASN1_TIME_free(tm);
3159 return ret;
3160}
3161
3162int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
3163 long days, long hours, long secs)
3164{
3165 int ret = 0;
3166 ASN1_TIME *tm = ASN1_TIME_new();
3167
3168 if (tm == NULL)
3169 goto end;
3170
3171 if (nextupdate == NULL) {
3172 if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
3173 goto end;
3174 } else {
3175 if (!ASN1_TIME_set_string_X509(tm, nextupdate))
3176 goto end;
3177 }
3178
3179 if (!X509_CRL_set1_nextUpdate(crl, tm))
3180 goto end;
3181
3182 ret = 1;
3183end:
3184 ASN1_TIME_free(tm);
3185 return ret;
3186}
3187
20967afb
RS
3188void make_uppercase(char *string)
3189{
3190 int i;
3191
3192 for (i = 0; string[i] != '\0'; i++)
3193 string[i] = toupper((unsigned char)string[i]);
3194}
a43ce58f 3195
28407698 3196/* This function is defined here due to visibility of bio_err */
a43ce58f
SL
3197int opt_printf_stderr(const char *fmt, ...)
3198{
3199 va_list ap;
3200 int ret;
3201
3202 va_start(ap, fmt);
3203 ret = BIO_vprintf(bio_err, fmt, ap);
3204 va_end(ap);
3205 return ret;
3206}
95214b43
SL
3207
3208OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
3209 const OSSL_PARAM *paramdefs)
3210{
3211 OSSL_PARAM *params = NULL;
3212 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
3213 size_t params_n;
3214 char *opt = "", *stmp, *vtmp = NULL;
e1dcac22 3215 int found = 1;
95214b43
SL
3216
3217 if (opts == NULL)
3218 return NULL;
3219
3220 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
3221 if (params == NULL)
3222 return NULL;
3223
3224 for (params_n = 0; params_n < sz; params_n++) {
3225 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
3226 if ((stmp = OPENSSL_strdup(opt)) == NULL
3227 || (vtmp = strchr(stmp, ':')) == NULL)
3228 goto err;
3229 /* Replace ':' with 0 to terminate the string pointed to by stmp */
3230 *vtmp = 0;
3231 /* Skip over the separator so that vmtp points to the value */
3232 vtmp++;
3233 if (!OSSL_PARAM_allocate_from_text(&params[params_n], paramdefs,
e1dcac22 3234 stmp, vtmp, strlen(vtmp), &found))
95214b43
SL
3235 goto err;
3236 OPENSSL_free(stmp);
3237 }
3238 params[params_n] = OSSL_PARAM_construct_end();
3239 return params;
3240err:
3241 OPENSSL_free(stmp);
e1dcac22
P
3242 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
3243 opt);
95214b43
SL
3244 ERR_print_errors(bio_err);
3245 app_params_free(params);
3246 return NULL;
3247}
3248
3249void app_params_free(OSSL_PARAM *params)
3250{
3251 int i;
3252
3253 if (params != NULL) {
3254 for (i = 0; params[i].key != NULL; ++i)
3255 OPENSSL_free(params[i].data);
3256 OPENSSL_free(params);
3257 }
3258}
a7e4ca5b
DDO
3259
3260EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose)
3261{
3262 EVP_PKEY *res = NULL;
3263
3264 if (verbose && alg != NULL) {
3265 BIO_printf(bio_err, "Generating %s key", alg);
3266 if (bits > 0)
3267 BIO_printf(bio_err, " with %d bits\n", bits);
3268 else
3269 BIO_printf(bio_err, "\n");
3270 }
3271 if (!RAND_status())
3272 BIO_printf(bio_err, "Warning: generating random key material may take a long time\n"
3273 "if the system has a poor entropy source\n");
3274 if (EVP_PKEY_keygen(ctx, &res) <= 0)
3275 app_bail_out("%s: Error generating %s key\n", opt_getprog(),
3276 alg != NULL ? alg : "asymmetric");
3277 return res;
3278}
3279
3280EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg)
3281{
3282 EVP_PKEY *res = NULL;
3283
3284 if (!RAND_status())
3285 BIO_printf(bio_err, "Warning: generating random key parameters may take a long time\n"
3286 "if the system has a poor entropy source\n");
3287 if (EVP_PKEY_paramgen(ctx, &res) <= 0)
3288 app_bail_out("%s: Generating %s key parameters failed\n",
3289 opt_getprog(), alg != NULL ? alg : "asymmetric");
3290 return res;
3291}