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