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