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