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