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