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