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