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