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