VirtualBox

source: vbox/trunk/src/libs/openssl-3.0.1/apps/lib/apps.c@ 94320

Last change on this file since 94320 was 94320, checked in by vboxsync, 3 years ago

libs/openssl-3.0.1: Export to OSE and fix copyright headers in Makefiles, bugref:10128

File size: 94.8 KB
Line 
1/*
2 * Copyright 1995-2021 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#ifndef OPENSSL_NO_ENGINE
19/* We need to use some deprecated APIs */
20# define OPENSSL_SUPPRESS_DEPRECATED
21# include <openssl/engine.h>
22#endif
23
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/types.h>
28#ifndef OPENSSL_NO_POSIX_IO
29# include <sys/stat.h>
30# include <fcntl.h>
31#endif
32#include <ctype.h>
33#include <errno.h>
34#include <openssl/err.h>
35#include <openssl/x509.h>
36#include <openssl/x509v3.h>
37#include <openssl/http.h>
38#include <openssl/pem.h>
39#include <openssl/store.h>
40#include <openssl/pkcs12.h>
41#include <openssl/ui.h>
42#include <openssl/safestack.h>
43#include <openssl/rsa.h>
44#include <openssl/rand.h>
45#include <openssl/bn.h>
46#include <openssl/ssl.h>
47#include <openssl/store.h>
48#include <openssl/core_names.h>
49#include "s_apps.h"
50#include "apps.h"
51
52#ifdef _WIN32
53static int WIN32_rename(const char *from, const char *to);
54# define rename(from,to) WIN32_rename((from),(to))
55#endif
56
57#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
58# include <conio.h>
59#endif
60
61#if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) || defined(__BORLANDC__)
62# define _kbhit kbhit
63#endif
64
65static BIO *bio_open_default_(const char *filename, char mode, int format,
66 int quiet);
67
68#define PASS_SOURCE_SIZE_MAX 4
69
70DEFINE_STACK_OF(CONF)
71
72typedef struct {
73 const char *name;
74 unsigned long flag;
75 unsigned long mask;
76} NAME_EX_TBL;
77
78static int set_table_opts(unsigned long *flags, const char *arg,
79 const NAME_EX_TBL * in_tbl);
80static int set_multi_opts(unsigned long *flags, const char *arg,
81 const NAME_EX_TBL * in_tbl);
82static
83int load_key_certs_crls_suppress(const char *uri, int format, int maybe_stdin,
84 const char *pass, const char *desc,
85 EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
86 EVP_PKEY **pparams,
87 X509 **pcert, STACK_OF(X509) **pcerts,
88 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls,
89 int suppress_decode_errors);
90
91int app_init(long mesgwin);
92
93int chopup_args(ARGS *arg, char *buf)
94{
95 int quoted;
96 char c = '\0', *p = NULL;
97
98 arg->argc = 0;
99 if (arg->size == 0) {
100 arg->size = 20;
101 arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space");
102 }
103
104 for (p = buf;;) {
105 /* Skip whitespace. */
106 while (*p && isspace(_UC(*p)))
107 p++;
108 if (*p == '\0')
109 break;
110
111 /* The start of something good :-) */
112 if (arg->argc >= arg->size) {
113 char **tmp;
114 arg->size += 20;
115 tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size);
116 if (tmp == NULL)
117 return 0;
118 arg->argv = tmp;
119 }
120 quoted = *p == '\'' || *p == '"';
121 if (quoted)
122 c = *p++;
123 arg->argv[arg->argc++] = p;
124
125 /* now look for the end of this */
126 if (quoted) {
127 while (*p && *p != c)
128 p++;
129 *p++ = '\0';
130 } else {
131 while (*p && !isspace(_UC(*p)))
132 p++;
133 if (*p)
134 *p++ = '\0';
135 }
136 }
137 arg->argv[arg->argc] = NULL;
138 return 1;
139}
140
141#ifndef APP_INIT
142int app_init(long mesgwin)
143{
144 return 1;
145}
146#endif
147
148int ctx_set_verify_locations(SSL_CTX *ctx,
149 const char *CAfile, int noCAfile,
150 const char *CApath, int noCApath,
151 const char *CAstore, int noCAstore)
152{
153 if (CAfile == NULL && CApath == NULL && CAstore == NULL) {
154 if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0)
155 return 0;
156 if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0)
157 return 0;
158 if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0)
159 return 0;
160
161 return 1;
162 }
163
164 if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile))
165 return 0;
166 if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath))
167 return 0;
168 if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore))
169 return 0;
170 return 1;
171}
172
173#ifndef OPENSSL_NO_CT
174
175int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
176{
177 if (path == NULL)
178 return SSL_CTX_set_default_ctlog_list_file(ctx);
179
180 return SSL_CTX_set_ctlog_list_file(ctx, path);
181}
182
183#endif
184
185static unsigned long nmflag = 0;
186static char nmflag_set = 0;
187
188int set_nameopt(const char *arg)
189{
190 int ret = set_name_ex(&nmflag, arg);
191
192 if (ret)
193 nmflag_set = 1;
194
195 return ret;
196}
197
198unsigned long get_nameopt(void)
199{
200 return (nmflag_set) ? nmflag : XN_FLAG_ONELINE;
201}
202
203void dump_cert_text(BIO *out, X509 *x)
204{
205 print_name(out, "subject=", X509_get_subject_name(x));
206 print_name(out, "issuer=", X509_get_issuer_name(x));
207}
208
209int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata)
210{
211 return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata);
212}
213
214
215static char *app_get_pass(const char *arg, int keepbio);
216
217char *get_passwd(const char *pass, const char *desc)
218{
219 char *result = NULL;
220
221 if (desc == NULL)
222 desc = "<unknown>";
223 if (!app_passwd(pass, NULL, &result, NULL))
224 BIO_printf(bio_err, "Error getting password for %s\n", desc);
225 if (pass != NULL && result == NULL) {
226 BIO_printf(bio_err,
227 "Trying plain input string (better precede with 'pass:')\n");
228 result = OPENSSL_strdup(pass);
229 if (result == NULL)
230 BIO_printf(bio_err, "Out of memory getting password for %s\n", desc);
231 }
232 return result;
233}
234
235int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2)
236{
237 int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0;
238
239 if (arg1 != NULL) {
240 *pass1 = app_get_pass(arg1, same);
241 if (*pass1 == NULL)
242 return 0;
243 } else if (pass1 != NULL) {
244 *pass1 = NULL;
245 }
246 if (arg2 != NULL) {
247 *pass2 = app_get_pass(arg2, same ? 2 : 0);
248 if (*pass2 == NULL)
249 return 0;
250 } else if (pass2 != NULL) {
251 *pass2 = NULL;
252 }
253 return 1;
254}
255
256static char *app_get_pass(const char *arg, int keepbio)
257{
258 static BIO *pwdbio = NULL;
259 char *tmp, tpass[APP_PASS_LEN];
260 int i;
261
262 /* PASS_SOURCE_SIZE_MAX = max number of chars before ':' in below strings */
263 if (strncmp(arg, "pass:", 5) == 0)
264 return OPENSSL_strdup(arg + 5);
265 if (strncmp(arg, "env:", 4) == 0) {
266 tmp = getenv(arg + 4);
267 if (tmp == NULL) {
268 BIO_printf(bio_err, "No environment variable %s\n", arg + 4);
269 return NULL;
270 }
271 return OPENSSL_strdup(tmp);
272 }
273 if (!keepbio || pwdbio == NULL) {
274 if (strncmp(arg, "file:", 5) == 0) {
275 pwdbio = BIO_new_file(arg + 5, "r");
276 if (pwdbio == NULL) {
277 BIO_printf(bio_err, "Can't open file %s\n", arg + 5);
278 return NULL;
279 }
280#if !defined(_WIN32)
281 /*
282 * Under _WIN32, which covers even Win64 and CE, file
283 * descriptors referenced by BIO_s_fd are not inherited
284 * by child process and therefore below is not an option.
285 * It could have been an option if bss_fd.c was operating
286 * on real Windows descriptors, such as those obtained
287 * with CreateFile.
288 */
289 } else if (strncmp(arg, "fd:", 3) == 0) {
290 BIO *btmp;
291 i = atoi(arg + 3);
292 if (i >= 0)
293 pwdbio = BIO_new_fd(i, BIO_NOCLOSE);
294 if ((i < 0) || !pwdbio) {
295 BIO_printf(bio_err, "Can't access file descriptor %s\n", arg + 3);
296 return NULL;
297 }
298 /*
299 * Can't do BIO_gets on an fd BIO so add a buffering BIO
300 */
301 btmp = BIO_new(BIO_f_buffer());
302 pwdbio = BIO_push(btmp, pwdbio);
303#endif
304 } else if (strcmp(arg, "stdin") == 0) {
305 pwdbio = dup_bio_in(FORMAT_TEXT);
306 if (pwdbio == NULL) {
307 BIO_printf(bio_err, "Can't open BIO for stdin\n");
308 return NULL;
309 }
310 } else {
311 /* argument syntax error; do not reveal too much about arg */
312 tmp = strchr(arg, ':');
313 if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX)
314 BIO_printf(bio_err,
315 "Invalid password argument, missing ':' within the first %d chars\n",
316 PASS_SOURCE_SIZE_MAX + 1);
317 else
318 BIO_printf(bio_err,
319 "Invalid password argument, starting with \"%.*s\"\n",
320 (int)(tmp - arg + 1), arg);
321 return NULL;
322 }
323 }
324 i = BIO_gets(pwdbio, tpass, APP_PASS_LEN);
325 if (keepbio != 1) {
326 BIO_free_all(pwdbio);
327 pwdbio = NULL;
328 }
329 if (i <= 0) {
330 BIO_printf(bio_err, "Error reading password from BIO\n");
331 return NULL;
332 }
333 tmp = strchr(tpass, '\n');
334 if (tmp != NULL)
335 *tmp = 0;
336 return OPENSSL_strdup(tpass);
337}
338
339CONF *app_load_config_bio(BIO *in, const char *filename)
340{
341 long errorline = -1;
342 CONF *conf;
343 int i;
344
345 conf = NCONF_new_ex(app_get0_libctx(), NULL);
346 i = NCONF_load_bio(conf, in, &errorline);
347 if (i > 0)
348 return conf;
349
350 if (errorline <= 0) {
351 BIO_printf(bio_err, "%s: Can't load ", opt_getprog());
352 } else {
353 BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(),
354 errorline);
355 }
356 if (filename != NULL)
357 BIO_printf(bio_err, "config file \"%s\"\n", filename);
358 else
359 BIO_printf(bio_err, "config input");
360
361 NCONF_free(conf);
362 return NULL;
363}
364
365CONF *app_load_config_verbose(const char *filename, int verbose)
366{
367 if (verbose) {
368 if (*filename == '\0')
369 BIO_printf(bio_err, "No configuration used\n");
370 else
371 BIO_printf(bio_err, "Using configuration from %s\n", filename);
372 }
373 return app_load_config_internal(filename, 0);
374}
375
376CONF *app_load_config_internal(const char *filename, int quiet)
377{
378 BIO *in;
379 CONF *conf;
380
381 if (filename == NULL || *filename != '\0') {
382 if ((in = bio_open_default_(filename, 'r', FORMAT_TEXT, quiet)) == NULL)
383 return NULL;
384 conf = app_load_config_bio(in, filename);
385 BIO_free(in);
386 } else {
387 /* Return empty config if filename is empty string. */
388 conf = NCONF_new_ex(app_get0_libctx(), NULL);
389 }
390 return conf;
391}
392
393int app_load_modules(const CONF *config)
394{
395 CONF *to_free = NULL;
396
397 if (config == NULL)
398 config = to_free = app_load_config_quiet(default_config_file);
399 if (config == NULL)
400 return 1;
401
402 if (CONF_modules_load(config, NULL, 0) <= 0) {
403 BIO_printf(bio_err, "Error configuring OpenSSL modules\n");
404 ERR_print_errors(bio_err);
405 NCONF_free(to_free);
406 return 0;
407 }
408 NCONF_free(to_free);
409 return 1;
410}
411
412int add_oid_section(CONF *conf)
413{
414 char *p;
415 STACK_OF(CONF_VALUE) *sktmp;
416 CONF_VALUE *cnf;
417 int i;
418
419 if ((p = NCONF_get_string(conf, NULL, "oid_section")) == NULL) {
420 ERR_clear_error();
421 return 1;
422 }
423 if ((sktmp = NCONF_get_section(conf, p)) == NULL) {
424 BIO_printf(bio_err, "problem loading oid section %s\n", p);
425 return 0;
426 }
427 for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
428 cnf = sk_CONF_VALUE_value(sktmp, i);
429 if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
430 BIO_printf(bio_err, "problem creating object %s=%s\n",
431 cnf->name, cnf->value);
432 return 0;
433 }
434 }
435 return 1;
436}
437
438CONF *app_load_config_modules(const char *configfile)
439{
440 CONF *conf = NULL;
441
442 if (configfile != NULL) {
443 if ((conf = app_load_config_verbose(configfile, 1)) == NULL)
444 return NULL;
445 if (configfile != default_config_file && !app_load_modules(conf)) {
446 NCONF_free(conf);
447 conf = NULL;
448 }
449 }
450 return conf;
451}
452
453#define IS_HTTP(uri) ((uri) != NULL \
454 && strncmp(uri, OSSL_HTTP_PREFIX, strlen(OSSL_HTTP_PREFIX)) == 0)
455#define IS_HTTPS(uri) ((uri) != NULL \
456 && strncmp(uri, OSSL_HTTPS_PREFIX, strlen(OSSL_HTTPS_PREFIX)) == 0)
457
458X509 *load_cert_pass(const char *uri, int format, int maybe_stdin,
459 const char *pass, const char *desc)
460{
461 X509 *cert = NULL;
462
463 if (desc == NULL)
464 desc = "certificate";
465 if (IS_HTTPS(uri))
466 BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
467 else if (IS_HTTP(uri))
468 cert = X509_load_http(uri, NULL, NULL, 0 /* timeout */);
469 else
470 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
471 NULL, NULL, NULL, &cert, NULL, NULL, NULL);
472 if (cert == NULL) {
473 BIO_printf(bio_err, "Unable to load %s\n", desc);
474 ERR_print_errors(bio_err);
475 }
476 return cert;
477}
478
479X509_CRL *load_crl(const char *uri, int format, int maybe_stdin,
480 const char *desc)
481{
482 X509_CRL *crl = NULL;
483
484 if (desc == NULL)
485 desc = "CRL";
486 if (IS_HTTPS(uri))
487 BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc);
488 else if (IS_HTTP(uri))
489 crl = X509_CRL_load_http(uri, NULL, NULL, 0 /* timeout */);
490 else
491 (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc,
492 NULL, NULL, NULL, NULL, NULL, &crl, NULL);
493 if (crl == NULL) {
494 BIO_printf(bio_err, "Unable to load %s\n", desc);
495 ERR_print_errors(bio_err);
496 }
497 return crl;
498}
499
500X509_REQ *load_csr(const char *file, int format, const char *desc)
501{
502 X509_REQ *req = NULL;
503 BIO *in;
504
505 if (format == FORMAT_UNDEF)
506 format = FORMAT_PEM;
507 if (desc == NULL)
508 desc = "CSR";
509 in = bio_open_default(file, 'r', format);
510 if (in == NULL)
511 goto end;
512
513 if (format == FORMAT_ASN1)
514 req = d2i_X509_REQ_bio(in, NULL);
515 else if (format == FORMAT_PEM)
516 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
517 else
518 print_format_error(format, OPT_FMT_PEMDER);
519
520 end:
521 if (req == NULL) {
522 BIO_printf(bio_err, "Unable to load %s\n", desc);
523 ERR_print_errors(bio_err);
524 }
525 BIO_free(in);
526 return req;
527}
528
529void cleanse(char *str)
530{
531 if (str != NULL)
532 OPENSSL_cleanse(str, strlen(str));
533}
534
535void clear_free(char *str)
536{
537 if (str != NULL)
538 OPENSSL_clear_free(str, strlen(str));
539}
540
541EVP_PKEY *load_key(const char *uri, int format, int may_stdin,
542 const char *pass, ENGINE *e, const char *desc)
543{
544 EVP_PKEY *pkey = NULL;
545 char *allocated_uri = NULL;
546
547 if (desc == NULL)
548 desc = "private key";
549
550 if (format == FORMAT_ENGINE) {
551 uri = allocated_uri = make_engine_uri(e, uri, desc);
552 }
553 (void)load_key_certs_crls(uri, format, may_stdin, pass, desc,
554 &pkey, NULL, NULL, NULL, NULL, NULL, NULL);
555
556 OPENSSL_free(allocated_uri);
557 return pkey;
558}
559
560EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin,
561 const char *pass, ENGINE *e, const char *desc)
562{
563 EVP_PKEY *pkey = NULL;
564 char *allocated_uri = NULL;
565
566 if (desc == NULL)
567 desc = "public key";
568
569 if (format == FORMAT_ENGINE) {
570 uri = allocated_uri = make_engine_uri(e, uri, desc);
571 }
572 (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc,
573 NULL, &pkey, NULL, NULL, NULL, NULL, NULL);
574
575 OPENSSL_free(allocated_uri);
576 return pkey;
577}
578
579EVP_PKEY *load_keyparams_suppress(const char *uri, int format, int maybe_stdin,
580 const char *keytype, const char *desc,
581 int suppress_decode_errors)
582{
583 EVP_PKEY *params = NULL;
584
585 if (desc == NULL)
586 desc = "key parameters";
587
588 (void)load_key_certs_crls_suppress(uri, format, maybe_stdin, NULL, desc,
589 NULL, NULL, &params, NULL, NULL, NULL,
590 NULL, suppress_decode_errors);
591 if (params != NULL && keytype != NULL && !EVP_PKEY_is_a(params, keytype)) {
592 if (!suppress_decode_errors) {
593 BIO_printf(bio_err,
594 "Unable to load %s from %s (unexpected parameters type)\n",
595 desc, uri);
596 ERR_print_errors(bio_err);
597 }
598 EVP_PKEY_free(params);
599 params = NULL;
600 }
601 return params;
602}
603
604EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin,
605 const char *keytype, const char *desc)
606{
607 return load_keyparams_suppress(uri, format, maybe_stdin, keytype, desc, 0);
608}
609
610void app_bail_out(char *fmt, ...)
611{
612 va_list args;
613
614 va_start(args, fmt);
615 BIO_vprintf(bio_err, fmt, args);
616 va_end(args);
617 ERR_print_errors(bio_err);
618 exit(EXIT_FAILURE);
619}
620
621void *app_malloc(size_t sz, const char *what)
622{
623 void *vp = OPENSSL_malloc(sz);
624
625 if (vp == NULL)
626 app_bail_out("%s: Could not allocate %zu bytes for %s\n",
627 opt_getprog(), sz, what);
628 return vp;
629}
630
631char *next_item(char *opt) /* in list separated by comma and/or space */
632{
633 /* advance to separator (comma or whitespace), if any */
634 while (*opt != ',' && !isspace(*opt) && *opt != '\0')
635 opt++;
636 if (*opt != '\0') {
637 /* terminate current item */
638 *opt++ = '\0';
639 /* skip over any whitespace after separator */
640 while (isspace(*opt))
641 opt++;
642 }
643 return *opt == '\0' ? NULL : opt; /* NULL indicates end of input */
644}
645
646static void warn_cert_msg(const char *uri, X509 *cert, const char *msg)
647{
648 char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
649
650 BIO_printf(bio_err, "Warning: certificate from '%s' with subject '%s' %s\n",
651 uri, subj, msg);
652 OPENSSL_free(subj);
653}
654
655static void warn_cert(const char *uri, X509 *cert, int warn_EE,
656 X509_VERIFY_PARAM *vpm)
657{
658 uint32_t ex_flags = X509_get_extension_flags(cert);
659 int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert),
660 X509_get0_notAfter(cert));
661
662 if (res != 0)
663 warn_cert_msg(uri, cert, res > 0 ? "has expired" : "not yet valid");
664 if (warn_EE && (ex_flags & EXFLAG_V1) == 0 && (ex_flags & EXFLAG_CA) == 0)
665 warn_cert_msg(uri, cert, "is not a CA cert");
666}
667
668static void warn_certs(const char *uri, STACK_OF(X509) *certs, int warn_EE,
669 X509_VERIFY_PARAM *vpm)
670{
671 int i;
672
673 for (i = 0; i < sk_X509_num(certs); i++)
674 warn_cert(uri, sk_X509_value(certs, i), warn_EE, vpm);
675}
676
677int load_cert_certs(const char *uri,
678 X509 **pcert, STACK_OF(X509) **pcerts,
679 int exclude_http, const char *pass, const char *desc,
680 X509_VERIFY_PARAM *vpm)
681{
682 int ret = 0;
683 char *pass_string;
684
685 if (exclude_http && (strncasecmp(uri, "http://", 7) == 0
686 || strncasecmp(uri, "https://", 8) == 0)) {
687 BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc);
688 return ret;
689 }
690 pass_string = get_passwd(pass, desc);
691 ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass_string, desc,
692 NULL, NULL, NULL,
693 pcert, pcerts, NULL, NULL);
694 clear_free(pass_string);
695
696 if (ret) {
697 if (pcert != NULL)
698 warn_cert(uri, *pcert, 0, vpm);
699 warn_certs(uri, *pcerts, 1, vpm);
700 } else {
701 sk_X509_pop_free(*pcerts, X509_free);
702 *pcerts = NULL;
703 }
704 return ret;
705}
706
707STACK_OF(X509) *load_certs_multifile(char *files, const char *pass,
708 const char *desc, X509_VERIFY_PARAM *vpm)
709{
710 STACK_OF(X509) *certs = NULL;
711 STACK_OF(X509) *result = sk_X509_new_null();
712
713 if (files == NULL)
714 goto err;
715 if (result == NULL)
716 goto oom;
717
718 while (files != NULL) {
719 char *next = next_item(files);
720
721 if (!load_cert_certs(files, NULL, &certs, 0, pass, desc, vpm))
722 goto err;
723 if (!X509_add_certs(result, certs,
724 X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
725 goto oom;
726 sk_X509_pop_free(certs, X509_free);
727 certs = NULL;
728 files = next;
729 }
730 return result;
731
732 oom:
733 BIO_printf(bio_err, "out of memory\n");
734 err:
735 sk_X509_pop_free(certs, X509_free);
736 sk_X509_pop_free(result, X509_free);
737 return NULL;
738}
739
740static X509_STORE *sk_X509_to_store(X509_STORE *store /* may be NULL */,
741 const STACK_OF(X509) *certs /* may NULL */)
742{
743 int i;
744
745 if (store == NULL)
746 store = X509_STORE_new();
747 if (store == NULL)
748 return NULL;
749 for (i = 0; i < sk_X509_num(certs); i++) {
750 if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) {
751 X509_STORE_free(store);
752 return NULL;
753 }
754 }
755 return store;
756}
757
758/*
759 * Create cert store structure with certificates read from given file(s).
760 * Returns pointer to created X509_STORE on success, NULL on error.
761 */
762X509_STORE *load_certstore(char *input, const char *pass, const char *desc,
763 X509_VERIFY_PARAM *vpm)
764{
765 X509_STORE *store = NULL;
766 STACK_OF(X509) *certs = NULL;
767
768 while (input != NULL) {
769 char *next = next_item(input);
770 int ok;
771
772 if (!load_cert_certs(input, NULL, &certs, 1, pass, desc, vpm)) {
773 X509_STORE_free(store);
774 return NULL;
775 }
776 ok = (store = sk_X509_to_store(store, certs)) != NULL;
777 sk_X509_pop_free(certs, X509_free);
778 certs = NULL;
779 if (!ok)
780 return NULL;
781 input = next;
782 }
783 return store;
784}
785
786/*
787 * Initialize or extend, if *certs != NULL, a certificate stack.
788 * The caller is responsible for freeing *certs if its value is left not NULL.
789 */
790int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs,
791 const char *pass, const char *desc)
792{
793 int was_NULL = *certs == NULL;
794 int ret = load_key_certs_crls(uri, FORMAT_UNDEF, maybe_stdin,
795 pass, desc, NULL, NULL,
796 NULL, NULL, certs, NULL, NULL);
797
798 if (!ret && was_NULL) {
799 sk_X509_pop_free(*certs, X509_free);
800 *certs = NULL;
801 }
802 return ret;
803}
804
805/*
806 * Initialize or extend, if *crls != NULL, a certificate stack.
807 * The caller is responsible for freeing *crls if its value is left not NULL.
808 */
809int load_crls(const char *uri, STACK_OF(X509_CRL) **crls,
810 const char *pass, const char *desc)
811{
812 int was_NULL = *crls == NULL;
813 int ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass, desc,
814 NULL, NULL, NULL,
815 NULL, NULL, NULL, crls);
816
817 if (!ret && was_NULL) {
818 sk_X509_CRL_pop_free(*crls, X509_CRL_free);
819 *crls = NULL;
820 }
821 return ret;
822}
823
824static const char *format2string(int format)
825{
826 switch(format) {
827 case FORMAT_PEM:
828 return "PEM";
829 case FORMAT_ASN1:
830 return "DER";
831 }
832 return NULL;
833}
834
835/* Set type expectation, but clear it if objects of different types expected. */
836#define SET_EXPECT(expect, val) ((expect) = (expect) < 0 ? (val) : ((expect) == (val) ? (val) : 0))
837/*
838 * Load those types of credentials for which the result pointer is not NULL.
839 * Reads from stdio if uri is NULL and maybe_stdin is nonzero.
840 * For non-NULL ppkey, pcert, and pcrl the first suitable value found is loaded.
841 * If pcerts is non-NULL and *pcerts == NULL then a new cert list is allocated.
842 * If pcerts is non-NULL then all available certificates are appended to *pcerts
843 * except any certificate assigned to *pcert.
844 * If pcrls is non-NULL and *pcrls == NULL then a new list of CRLs is allocated.
845 * If pcrls is non-NULL then all available CRLs are appended to *pcerts
846 * except any CRL assigned to *pcrl.
847 * In any case (also on error) the caller is responsible for freeing all members
848 * of *pcerts and *pcrls (as far as they are not NULL).
849 */
850static
851int load_key_certs_crls_suppress(const char *uri, int format, int maybe_stdin,
852 const char *pass, const char *desc,
853 EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
854 EVP_PKEY **pparams,
855 X509 **pcert, STACK_OF(X509) **pcerts,
856 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls,
857 int suppress_decode_errors)
858{
859 PW_CB_DATA uidata;
860 OSSL_STORE_CTX *ctx = NULL;
861 OSSL_LIB_CTX *libctx = app_get0_libctx();
862 const char *propq = app_get0_propq();
863 int ncerts = 0;
864 int ncrls = 0;
865 const char *failed =
866 ppkey != NULL ? "key" : ppubkey != NULL ? "public key" :
867 pparams != NULL ? "params" : pcert != NULL ? "cert" :
868 pcrl != NULL ? "CRL" : pcerts != NULL ? "certs" :
869 pcrls != NULL ? "CRLs" : NULL;
870 int cnt_expectations = 0;
871 int expect = -1;
872 const char *input_type;
873 OSSL_PARAM itp[2];
874 const OSSL_PARAM *params = NULL;
875
876 if (ppkey != NULL) {
877 *ppkey = NULL;
878 cnt_expectations++;
879 SET_EXPECT(expect, OSSL_STORE_INFO_PKEY);
880 }
881 if (ppubkey != NULL) {
882 *ppubkey = NULL;
883 cnt_expectations++;
884 SET_EXPECT(expect, OSSL_STORE_INFO_PUBKEY);
885 }
886 if (pparams != NULL) {
887 *pparams = NULL;
888 cnt_expectations++;
889 SET_EXPECT(expect, OSSL_STORE_INFO_PARAMS);
890 }
891 if (pcert != NULL) {
892 *pcert = NULL;
893 cnt_expectations++;
894 SET_EXPECT(expect, OSSL_STORE_INFO_CERT);
895 }
896 if (pcerts != NULL) {
897 if (*pcerts == NULL && (*pcerts = sk_X509_new_null()) == NULL) {
898 BIO_printf(bio_err, "Out of memory loading");
899 goto end;
900 }
901 cnt_expectations++;
902 SET_EXPECT(expect, OSSL_STORE_INFO_CERT);
903 }
904 if (pcrl != NULL) {
905 *pcrl = NULL;
906 cnt_expectations++;
907 SET_EXPECT(expect, OSSL_STORE_INFO_CRL);
908 }
909 if (pcrls != NULL) {
910 if (*pcrls == NULL && (*pcrls = sk_X509_CRL_new_null()) == NULL) {
911 BIO_printf(bio_err, "Out of memory loading");
912 goto end;
913 }
914 cnt_expectations++;
915 SET_EXPECT(expect, OSSL_STORE_INFO_CRL);
916 }
917 if (cnt_expectations == 0) {
918 BIO_printf(bio_err, "Internal error: nothing to load from %s\n",
919 uri != NULL ? uri : "<stdin>");
920 return 0;
921 }
922
923 uidata.password = pass;
924 uidata.prompt_info = uri;
925
926 if ((input_type = format2string(format)) != NULL) {
927 itp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE,
928 (char *)input_type, 0);
929 itp[1] = OSSL_PARAM_construct_end();
930 params = itp;
931 }
932
933 if (uri == NULL) {
934 BIO *bio;
935
936 if (!maybe_stdin) {
937 BIO_printf(bio_err, "No filename or uri specified for loading");
938 goto end;
939 }
940 uri = "<stdin>";
941 unbuffer(stdin);
942 bio = BIO_new_fp(stdin, 0);
943 if (bio != NULL) {
944 ctx = OSSL_STORE_attach(bio, "file", libctx, propq,
945 get_ui_method(), &uidata, params,
946 NULL, NULL);
947 BIO_free(bio);
948 }
949 } else {
950 ctx = OSSL_STORE_open_ex(uri, libctx, propq, get_ui_method(), &uidata,
951 params, NULL, NULL);
952 }
953 if (ctx == NULL) {
954 BIO_printf(bio_err, "Could not open file or uri for loading");
955 goto end;
956 }
957 if (expect > 0 && !OSSL_STORE_expect(ctx, expect))
958 goto end;
959
960 failed = NULL;
961 while (cnt_expectations > 0 && !OSSL_STORE_eof(ctx)) {
962 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
963 int type, ok = 1;
964
965 /*
966 * This can happen (for example) if we attempt to load a file with
967 * multiple different types of things in it - but the thing we just
968 * tried to load wasn't one of the ones we wanted, e.g. if we're trying
969 * to load a certificate but the file has both the private key and the
970 * certificate in it. We just retry until eof.
971 */
972 if (info == NULL) {
973 continue;
974 }
975
976 type = OSSL_STORE_INFO_get_type(info);
977 switch (type) {
978 case OSSL_STORE_INFO_PKEY:
979 if (ppkey != NULL && *ppkey == NULL) {
980 ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL;
981 cnt_expectations -= ok;
982 }
983 /*
984 * An EVP_PKEY with private parts also holds the public parts,
985 * so if the caller asked for a public key, and we got a private
986 * key, we can still pass it back.
987 */
988 if (ok && ppubkey != NULL && *ppubkey == NULL) {
989 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL);
990 cnt_expectations -= ok;
991 }
992 break;
993 case OSSL_STORE_INFO_PUBKEY:
994 if (ppubkey != NULL && *ppubkey == NULL) {
995 ok = ((*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL);
996 cnt_expectations -= ok;
997 }
998 break;
999 case OSSL_STORE_INFO_PARAMS:
1000 if (pparams != NULL && *pparams == NULL) {
1001 ok = ((*pparams = OSSL_STORE_INFO_get1_PARAMS(info)) != NULL);
1002 cnt_expectations -= ok;
1003 }
1004 break;
1005 case OSSL_STORE_INFO_CERT:
1006 if (pcert != NULL && *pcert == NULL) {
1007 ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL;
1008 cnt_expectations -= ok;
1009 }
1010 else if (pcerts != NULL)
1011 ok = X509_add_cert(*pcerts,
1012 OSSL_STORE_INFO_get1_CERT(info),
1013 X509_ADD_FLAG_DEFAULT);
1014 ncerts += ok;
1015 break;
1016 case OSSL_STORE_INFO_CRL:
1017 if (pcrl != NULL && *pcrl == NULL) {
1018 ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL;
1019 cnt_expectations -= ok;
1020 }
1021 else if (pcrls != NULL)
1022 ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info));
1023 ncrls += ok;
1024 break;
1025 default:
1026 /* skip any other type */
1027 break;
1028 }
1029 OSSL_STORE_INFO_free(info);
1030 if (!ok) {
1031 failed = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type);
1032 BIO_printf(bio_err, "Error reading");
1033 break;
1034 }
1035 }
1036
1037 end:
1038 OSSL_STORE_close(ctx);
1039 if (failed == NULL) {
1040 int any = 0;
1041
1042 if ((ppkey != NULL && *ppkey == NULL)
1043 || (ppubkey != NULL && *ppubkey == NULL)) {
1044 failed = "key";
1045 } else if (pparams != NULL && *pparams == NULL) {
1046 failed = "params";
1047 } else if ((pcert != NULL || pcerts != NULL) && ncerts == 0) {
1048 if (pcert == NULL)
1049 any = 1;
1050 failed = "cert";
1051 } else if ((pcrl != NULL || pcrls != NULL) && ncrls == 0) {
1052 if (pcrl == NULL)
1053 any = 1;
1054 failed = "CRL";
1055 }
1056 if (!suppress_decode_errors) {
1057 if (failed != NULL)
1058 BIO_printf(bio_err, "Could not read");
1059 if (any)
1060 BIO_printf(bio_err, " any");
1061 }
1062 }
1063 if (!suppress_decode_errors && failed != NULL) {
1064 if (desc != NULL && strstr(desc, failed) != NULL) {
1065 BIO_printf(bio_err, " %s", desc);
1066 } else {
1067 BIO_printf(bio_err, " %s", failed);
1068 if (desc != NULL)
1069 BIO_printf(bio_err, " of %s", desc);
1070 }
1071 if (uri != NULL)
1072 BIO_printf(bio_err, " from %s", uri);
1073 BIO_printf(bio_err, "\n");
1074 ERR_print_errors(bio_err);
1075 }
1076 if (suppress_decode_errors || failed == NULL)
1077 /* clear any spurious errors */
1078 ERR_clear_error();
1079 return failed == NULL;
1080}
1081
1082int load_key_certs_crls(const char *uri, int format, int maybe_stdin,
1083 const char *pass, const char *desc,
1084 EVP_PKEY **ppkey, EVP_PKEY **ppubkey,
1085 EVP_PKEY **pparams,
1086 X509 **pcert, STACK_OF(X509) **pcerts,
1087 X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls)
1088{
1089 return load_key_certs_crls_suppress(uri, format, maybe_stdin, pass, desc,
1090 ppkey, ppubkey, pparams, pcert, pcerts,
1091 pcrl, pcrls, 0);
1092}
1093
1094#define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
1095/* Return error for unknown extensions */
1096#define X509V3_EXT_DEFAULT 0
1097/* Print error for unknown extensions */
1098#define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
1099/* ASN1 parse unknown extensions */
1100#define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
1101/* BIO_dump unknown extensions */
1102#define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
1103
1104#define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \
1105 X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION)
1106
1107int set_cert_ex(unsigned long *flags, const char *arg)
1108{
1109 static const NAME_EX_TBL cert_tbl[] = {
1110 {"compatible", X509_FLAG_COMPAT, 0xffffffffl},
1111 {"ca_default", X509_FLAG_CA, 0xffffffffl},
1112 {"no_header", X509_FLAG_NO_HEADER, 0},
1113 {"no_version", X509_FLAG_NO_VERSION, 0},
1114 {"no_serial", X509_FLAG_NO_SERIAL, 0},
1115 {"no_signame", X509_FLAG_NO_SIGNAME, 0},
1116 {"no_validity", X509_FLAG_NO_VALIDITY, 0},
1117 {"no_subject", X509_FLAG_NO_SUBJECT, 0},
1118 {"no_issuer", X509_FLAG_NO_ISSUER, 0},
1119 {"no_pubkey", X509_FLAG_NO_PUBKEY, 0},
1120 {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0},
1121 {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0},
1122 {"no_aux", X509_FLAG_NO_AUX, 0},
1123 {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0},
1124 {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK},
1125 {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1126 {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1127 {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK},
1128 {NULL, 0, 0}
1129 };
1130 return set_multi_opts(flags, arg, cert_tbl);
1131}
1132
1133int set_name_ex(unsigned long *flags, const char *arg)
1134{
1135 static const NAME_EX_TBL ex_tbl[] = {
1136 {"esc_2253", ASN1_STRFLGS_ESC_2253, 0},
1137 {"esc_2254", ASN1_STRFLGS_ESC_2254, 0},
1138 {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0},
1139 {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0},
1140 {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0},
1141 {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0},
1142 {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0},
1143 {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0},
1144 {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0},
1145 {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0},
1146 {"dump_der", ASN1_STRFLGS_DUMP_DER, 0},
1147 {"compat", XN_FLAG_COMPAT, 0xffffffffL},
1148 {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK},
1149 {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK},
1150 {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK},
1151 {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK},
1152 {"dn_rev", XN_FLAG_DN_REV, 0},
1153 {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK},
1154 {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK},
1155 {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK},
1156 {"align", XN_FLAG_FN_ALIGN, 0},
1157 {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK},
1158 {"space_eq", XN_FLAG_SPC_EQ, 0},
1159 {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0},
1160 {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL},
1161 {"oneline", XN_FLAG_ONELINE, 0xffffffffL},
1162 {"multiline", XN_FLAG_MULTILINE, 0xffffffffL},
1163 {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL},
1164 {NULL, 0, 0}
1165 };
1166 if (set_multi_opts(flags, arg, ex_tbl) == 0)
1167 return 0;
1168 if (*flags != XN_FLAG_COMPAT
1169 && (*flags & XN_FLAG_SEP_MASK) == 0)
1170 *flags |= XN_FLAG_SEP_CPLUS_SPC;
1171 return 1;
1172}
1173
1174int set_dateopt(unsigned long *dateopt, const char *arg)
1175{
1176 if (strcasecmp(arg, "rfc_822") == 0)
1177 *dateopt = ASN1_DTFLGS_RFC822;
1178 else if (strcasecmp(arg, "iso_8601") == 0)
1179 *dateopt = ASN1_DTFLGS_ISO8601;
1180 return 0;
1181}
1182
1183int set_ext_copy(int *copy_type, const char *arg)
1184{
1185 if (strcasecmp(arg, "none") == 0)
1186 *copy_type = EXT_COPY_NONE;
1187 else if (strcasecmp(arg, "copy") == 0)
1188 *copy_type = EXT_COPY_ADD;
1189 else if (strcasecmp(arg, "copyall") == 0)
1190 *copy_type = EXT_COPY_ALL;
1191 else
1192 return 0;
1193 return 1;
1194}
1195
1196int copy_extensions(X509 *x, X509_REQ *req, int copy_type)
1197{
1198 STACK_OF(X509_EXTENSION) *exts;
1199 int i, ret = 0;
1200
1201 if (x == NULL || req == NULL)
1202 return 0;
1203 if (copy_type == EXT_COPY_NONE)
1204 return 1;
1205 exts = X509_REQ_get_extensions(req);
1206
1207 for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
1208 X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
1209 ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext);
1210 int idx = X509_get_ext_by_OBJ(x, obj, -1);
1211
1212 /* Does extension exist in target? */
1213 if (idx != -1) {
1214 /* If normal copy don't override existing extension */
1215 if (copy_type == EXT_COPY_ADD)
1216 continue;
1217 /* Delete all extensions of same type */
1218 do {
1219 X509_EXTENSION_free(X509_delete_ext(x, idx));
1220 idx = X509_get_ext_by_OBJ(x, obj, -1);
1221 } while (idx != -1);
1222 }
1223 if (!X509_add_ext(x, ext, -1))
1224 goto end;
1225 }
1226 ret = 1;
1227
1228 end:
1229 sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
1230 return ret;
1231}
1232
1233static int set_multi_opts(unsigned long *flags, const char *arg,
1234 const NAME_EX_TBL * in_tbl)
1235{
1236 STACK_OF(CONF_VALUE) *vals;
1237 CONF_VALUE *val;
1238 int i, ret = 1;
1239 if (!arg)
1240 return 0;
1241 vals = X509V3_parse_list(arg);
1242 for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
1243 val = sk_CONF_VALUE_value(vals, i);
1244 if (!set_table_opts(flags, val->name, in_tbl))
1245 ret = 0;
1246 }
1247 sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
1248 return ret;
1249}
1250
1251static int set_table_opts(unsigned long *flags, const char *arg,
1252 const NAME_EX_TBL * in_tbl)
1253{
1254 char c;
1255 const NAME_EX_TBL *ptbl;
1256 c = arg[0];
1257
1258 if (c == '-') {
1259 c = 0;
1260 arg++;
1261 } else if (c == '+') {
1262 c = 1;
1263 arg++;
1264 } else {
1265 c = 1;
1266 }
1267
1268 for (ptbl = in_tbl; ptbl->name; ptbl++) {
1269 if (strcasecmp(arg, ptbl->name) == 0) {
1270 *flags &= ~ptbl->mask;
1271 if (c)
1272 *flags |= ptbl->flag;
1273 else
1274 *flags &= ~ptbl->flag;
1275 return 1;
1276 }
1277 }
1278 return 0;
1279}
1280
1281void print_name(BIO *out, const char *title, const X509_NAME *nm)
1282{
1283 char *buf;
1284 char mline = 0;
1285 int indent = 0;
1286 unsigned long lflags = get_nameopt();
1287
1288 if (out == NULL)
1289 return;
1290 if (title != NULL)
1291 BIO_puts(out, title);
1292 if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
1293 mline = 1;
1294 indent = 4;
1295 }
1296 if (lflags == XN_FLAG_COMPAT) {
1297 buf = X509_NAME_oneline(nm, 0, 0);
1298 BIO_puts(out, buf);
1299 BIO_puts(out, "\n");
1300 OPENSSL_free(buf);
1301 } else {
1302 if (mline)
1303 BIO_puts(out, "\n");
1304 X509_NAME_print_ex(out, nm, indent, lflags);
1305 BIO_puts(out, "\n");
1306 }
1307}
1308
1309void print_bignum_var(BIO *out, const BIGNUM *in, const char *var,
1310 int len, unsigned char *buffer)
1311{
1312 BIO_printf(out, " static unsigned char %s_%d[] = {", var, len);
1313 if (BN_is_zero(in)) {
1314 BIO_printf(out, "\n 0x00");
1315 } else {
1316 int i, l;
1317
1318 l = BN_bn2bin(in, buffer);
1319 for (i = 0; i < l; i++) {
1320 BIO_printf(out, (i % 10) == 0 ? "\n " : " ");
1321 if (i < l - 1)
1322 BIO_printf(out, "0x%02X,", buffer[i]);
1323 else
1324 BIO_printf(out, "0x%02X", buffer[i]);
1325 }
1326 }
1327 BIO_printf(out, "\n };\n");
1328}
1329
1330void print_array(BIO *out, const char* title, int len, const unsigned char* d)
1331{
1332 int i;
1333
1334 BIO_printf(out, "unsigned char %s[%d] = {", title, len);
1335 for (i = 0; i < len; i++) {
1336 if ((i % 10) == 0)
1337 BIO_printf(out, "\n ");
1338 if (i < len - 1)
1339 BIO_printf(out, "0x%02X, ", d[i]);
1340 else
1341 BIO_printf(out, "0x%02X", d[i]);
1342 }
1343 BIO_printf(out, "\n};\n");
1344}
1345
1346X509_STORE *setup_verify(const char *CAfile, int noCAfile,
1347 const char *CApath, int noCApath,
1348 const char *CAstore, int noCAstore)
1349{
1350 X509_STORE *store = X509_STORE_new();
1351 X509_LOOKUP *lookup;
1352 OSSL_LIB_CTX *libctx = app_get0_libctx();
1353 const char *propq = app_get0_propq();
1354
1355 if (store == NULL)
1356 goto end;
1357
1358 if (CAfile != NULL || !noCAfile) {
1359 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
1360 if (lookup == NULL)
1361 goto end;
1362 if (CAfile != NULL) {
1363 if (!X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM,
1364 libctx, propq)) {
1365 BIO_printf(bio_err, "Error loading file %s\n", CAfile);
1366 goto end;
1367 }
1368 } else {
1369 X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT,
1370 libctx, propq);
1371 }
1372 }
1373
1374 if (CApath != NULL || !noCApath) {
1375 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1376 if (lookup == NULL)
1377 goto end;
1378 if (CApath != NULL) {
1379 if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) {
1380 BIO_printf(bio_err, "Error loading directory %s\n", CApath);
1381 goto end;
1382 }
1383 } else {
1384 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1385 }
1386 }
1387
1388 if (CAstore != NULL || !noCAstore) {
1389 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store());
1390 if (lookup == NULL)
1391 goto end;
1392 if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) {
1393 if (CAstore != NULL)
1394 BIO_printf(bio_err, "Error loading store URI %s\n", CAstore);
1395 goto end;
1396 }
1397 }
1398
1399 ERR_clear_error();
1400 return store;
1401 end:
1402 ERR_print_errors(bio_err);
1403 X509_STORE_free(store);
1404 return NULL;
1405}
1406
1407static unsigned long index_serial_hash(const OPENSSL_CSTRING *a)
1408{
1409 const char *n;
1410
1411 n = a[DB_serial];
1412 while (*n == '0')
1413 n++;
1414 return OPENSSL_LH_strhash(n);
1415}
1416
1417static int index_serial_cmp(const OPENSSL_CSTRING *a,
1418 const OPENSSL_CSTRING *b)
1419{
1420 const char *aa, *bb;
1421
1422 for (aa = a[DB_serial]; *aa == '0'; aa++) ;
1423 for (bb = b[DB_serial]; *bb == '0'; bb++) ;
1424 return strcmp(aa, bb);
1425}
1426
1427static int index_name_qual(char **a)
1428{
1429 return (a[0][0] == 'V');
1430}
1431
1432static unsigned long index_name_hash(const OPENSSL_CSTRING *a)
1433{
1434 return OPENSSL_LH_strhash(a[DB_name]);
1435}
1436
1437int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b)
1438{
1439 return strcmp(a[DB_name], b[DB_name]);
1440}
1441
1442static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING)
1443static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING)
1444static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING)
1445static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING)
1446#undef BSIZE
1447#define BSIZE 256
1448BIGNUM *load_serial(const char *serialfile, int create, ASN1_INTEGER **retai)
1449{
1450 BIO *in = NULL;
1451 BIGNUM *ret = NULL;
1452 char buf[1024];
1453 ASN1_INTEGER *ai = NULL;
1454
1455 ai = ASN1_INTEGER_new();
1456 if (ai == NULL)
1457 goto err;
1458
1459 in = BIO_new_file(serialfile, "r");
1460 if (in == NULL) {
1461 if (!create) {
1462 perror(serialfile);
1463 goto err;
1464 }
1465 ERR_clear_error();
1466 ret = BN_new();
1467 if (ret == NULL || !rand_serial(ret, ai))
1468 BIO_printf(bio_err, "Out of memory\n");
1469 } else {
1470 if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) {
1471 BIO_printf(bio_err, "Unable to load number from %s\n",
1472 serialfile);
1473 goto err;
1474 }
1475 ret = ASN1_INTEGER_to_BN(ai, NULL);
1476 if (ret == NULL) {
1477 BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n");
1478 goto err;
1479 }
1480 }
1481
1482 if (ret && retai) {
1483 *retai = ai;
1484 ai = NULL;
1485 }
1486 err:
1487 ERR_print_errors(bio_err);
1488 BIO_free(in);
1489 ASN1_INTEGER_free(ai);
1490 return ret;
1491}
1492
1493int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial,
1494 ASN1_INTEGER **retai)
1495{
1496 char buf[1][BSIZE];
1497 BIO *out = NULL;
1498 int ret = 0;
1499 ASN1_INTEGER *ai = NULL;
1500 int j;
1501
1502 if (suffix == NULL)
1503 j = strlen(serialfile);
1504 else
1505 j = strlen(serialfile) + strlen(suffix) + 1;
1506 if (j >= BSIZE) {
1507 BIO_printf(bio_err, "File name too long\n");
1508 goto err;
1509 }
1510
1511 if (suffix == NULL)
1512 OPENSSL_strlcpy(buf[0], serialfile, BSIZE);
1513 else {
1514#ifndef OPENSSL_SYS_VMS
1515 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix);
1516#else
1517 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix);
1518#endif
1519 }
1520 out = BIO_new_file(buf[0], "w");
1521 if (out == NULL) {
1522 goto err;
1523 }
1524
1525 if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) {
1526 BIO_printf(bio_err, "error converting serial to ASN.1 format\n");
1527 goto err;
1528 }
1529 i2a_ASN1_INTEGER(out, ai);
1530 BIO_puts(out, "\n");
1531 ret = 1;
1532 if (retai) {
1533 *retai = ai;
1534 ai = NULL;
1535 }
1536 err:
1537 if (!ret)
1538 ERR_print_errors(bio_err);
1539 BIO_free_all(out);
1540 ASN1_INTEGER_free(ai);
1541 return ret;
1542}
1543
1544int rotate_serial(const char *serialfile, const char *new_suffix,
1545 const char *old_suffix)
1546{
1547 char buf[2][BSIZE];
1548 int i, j;
1549
1550 i = strlen(serialfile) + strlen(old_suffix);
1551 j = strlen(serialfile) + strlen(new_suffix);
1552 if (i > j)
1553 j = i;
1554 if (j + 1 >= BSIZE) {
1555 BIO_printf(bio_err, "File name too long\n");
1556 goto err;
1557 }
1558#ifndef OPENSSL_SYS_VMS
1559 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix);
1560 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix);
1561#else
1562 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix);
1563 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix);
1564#endif
1565 if (rename(serialfile, buf[1]) < 0 && errno != ENOENT
1566#ifdef ENOTDIR
1567 && errno != ENOTDIR
1568#endif
1569 ) {
1570 BIO_printf(bio_err,
1571 "Unable to rename %s to %s\n", serialfile, buf[1]);
1572 perror("reason");
1573 goto err;
1574 }
1575 if (rename(buf[0], serialfile) < 0) {
1576 BIO_printf(bio_err,
1577 "Unable to rename %s to %s\n", buf[0], serialfile);
1578 perror("reason");
1579 rename(buf[1], serialfile);
1580 goto err;
1581 }
1582 return 1;
1583 err:
1584 ERR_print_errors(bio_err);
1585 return 0;
1586}
1587
1588int rand_serial(BIGNUM *b, ASN1_INTEGER *ai)
1589{
1590 BIGNUM *btmp;
1591 int ret = 0;
1592
1593 btmp = b == NULL ? BN_new() : b;
1594 if (btmp == NULL)
1595 return 0;
1596
1597 if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY))
1598 goto error;
1599 if (ai && !BN_to_ASN1_INTEGER(btmp, ai))
1600 goto error;
1601
1602 ret = 1;
1603
1604 error:
1605
1606 if (btmp != b)
1607 BN_free(btmp);
1608
1609 return ret;
1610}
1611
1612CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr)
1613{
1614 CA_DB *retdb = NULL;
1615 TXT_DB *tmpdb = NULL;
1616 BIO *in;
1617 CONF *dbattr_conf = NULL;
1618 char buf[BSIZE];
1619#ifndef OPENSSL_NO_POSIX_IO
1620 FILE *dbfp;
1621 struct stat dbst;
1622#endif
1623
1624 in = BIO_new_file(dbfile, "r");
1625 if (in == NULL)
1626 goto err;
1627
1628#ifndef OPENSSL_NO_POSIX_IO
1629 BIO_get_fp(in, &dbfp);
1630 if (fstat(fileno(dbfp), &dbst) == -1) {
1631 ERR_raise_data(ERR_LIB_SYS, errno,
1632 "calling fstat(%s)", dbfile);
1633 goto err;
1634 }
1635#endif
1636
1637 if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL)
1638 goto err;
1639
1640#ifndef OPENSSL_SYS_VMS
1641 BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile);
1642#else
1643 BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile);
1644#endif
1645 dbattr_conf = app_load_config_quiet(buf);
1646
1647 retdb = app_malloc(sizeof(*retdb), "new DB");
1648 retdb->db = tmpdb;
1649 tmpdb = NULL;
1650 if (db_attr)
1651 retdb->attributes = *db_attr;
1652 else {
1653 retdb->attributes.unique_subject = 1;
1654 }
1655
1656 if (dbattr_conf) {
1657 char *p = NCONF_get_string(dbattr_conf, NULL, "unique_subject");
1658 if (p) {
1659 retdb->attributes.unique_subject = parse_yesno(p, 1);
1660 }
1661 }
1662
1663 retdb->dbfname = OPENSSL_strdup(dbfile);
1664#ifndef OPENSSL_NO_POSIX_IO
1665 retdb->dbst = dbst;
1666#endif
1667
1668 err:
1669 ERR_print_errors(bio_err);
1670 NCONF_free(dbattr_conf);
1671 TXT_DB_free(tmpdb);
1672 BIO_free_all(in);
1673 return retdb;
1674}
1675
1676/*
1677 * Returns > 0 on success, <= 0 on error
1678 */
1679int index_index(CA_DB *db)
1680{
1681 if (!TXT_DB_create_index(db->db, DB_serial, NULL,
1682 LHASH_HASH_FN(index_serial),
1683 LHASH_COMP_FN(index_serial))) {
1684 BIO_printf(bio_err,
1685 "Error creating serial number index:(%ld,%ld,%ld)\n",
1686 db->db->error, db->db->arg1, db->db->arg2);
1687 goto err;
1688 }
1689
1690 if (db->attributes.unique_subject
1691 && !TXT_DB_create_index(db->db, DB_name, index_name_qual,
1692 LHASH_HASH_FN(index_name),
1693 LHASH_COMP_FN(index_name))) {
1694 BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n",
1695 db->db->error, db->db->arg1, db->db->arg2);
1696 goto err;
1697 }
1698 return 1;
1699 err:
1700 ERR_print_errors(bio_err);
1701 return 0;
1702}
1703
1704int save_index(const char *dbfile, const char *suffix, CA_DB *db)
1705{
1706 char buf[3][BSIZE];
1707 BIO *out;
1708 int j;
1709
1710 j = strlen(dbfile) + strlen(suffix);
1711 if (j + 6 >= BSIZE) {
1712 BIO_printf(bio_err, "File name too long\n");
1713 goto err;
1714 }
1715#ifndef OPENSSL_SYS_VMS
1716 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile);
1717 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix);
1718 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix);
1719#else
1720 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile);
1721 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix);
1722 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix);
1723#endif
1724 out = BIO_new_file(buf[0], "w");
1725 if (out == NULL) {
1726 perror(dbfile);
1727 BIO_printf(bio_err, "Unable to open '%s'\n", dbfile);
1728 goto err;
1729 }
1730 j = TXT_DB_write(out, db->db);
1731 BIO_free(out);
1732 if (j <= 0)
1733 goto err;
1734
1735 out = BIO_new_file(buf[1], "w");
1736 if (out == NULL) {
1737 perror(buf[2]);
1738 BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]);
1739 goto err;
1740 }
1741 BIO_printf(out, "unique_subject = %s\n",
1742 db->attributes.unique_subject ? "yes" : "no");
1743 BIO_free(out);
1744
1745 return 1;
1746 err:
1747 ERR_print_errors(bio_err);
1748 return 0;
1749}
1750
1751int rotate_index(const char *dbfile, const char *new_suffix,
1752 const char *old_suffix)
1753{
1754 char buf[5][BSIZE];
1755 int i, j;
1756
1757 i = strlen(dbfile) + strlen(old_suffix);
1758 j = strlen(dbfile) + strlen(new_suffix);
1759 if (i > j)
1760 j = i;
1761 if (j + 6 >= BSIZE) {
1762 BIO_printf(bio_err, "File name too long\n");
1763 goto err;
1764 }
1765#ifndef OPENSSL_SYS_VMS
1766 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile);
1767 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix);
1768 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix);
1769 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix);
1770 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix);
1771#else
1772 j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile);
1773 j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix);
1774 j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix);
1775 j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix);
1776 j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix);
1777#endif
1778 if (rename(dbfile, buf[1]) < 0 && errno != ENOENT
1779#ifdef ENOTDIR
1780 && errno != ENOTDIR
1781#endif
1782 ) {
1783 BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]);
1784 perror("reason");
1785 goto err;
1786 }
1787 if (rename(buf[0], dbfile) < 0) {
1788 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile);
1789 perror("reason");
1790 rename(buf[1], dbfile);
1791 goto err;
1792 }
1793 if (rename(buf[4], buf[3]) < 0 && errno != ENOENT
1794#ifdef ENOTDIR
1795 && errno != ENOTDIR
1796#endif
1797 ) {
1798 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]);
1799 perror("reason");
1800 rename(dbfile, buf[0]);
1801 rename(buf[1], dbfile);
1802 goto err;
1803 }
1804 if (rename(buf[2], buf[4]) < 0) {
1805 BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]);
1806 perror("reason");
1807 rename(buf[3], buf[4]);
1808 rename(dbfile, buf[0]);
1809 rename(buf[1], dbfile);
1810 goto err;
1811 }
1812 return 1;
1813 err:
1814 ERR_print_errors(bio_err);
1815 return 0;
1816}
1817
1818void free_index(CA_DB *db)
1819{
1820 if (db) {
1821 TXT_DB_free(db->db);
1822 OPENSSL_free(db->dbfname);
1823 OPENSSL_free(db);
1824 }
1825}
1826
1827int parse_yesno(const char *str, int def)
1828{
1829 if (str) {
1830 switch (*str) {
1831 case 'f': /* false */
1832 case 'F': /* FALSE */
1833 case 'n': /* no */
1834 case 'N': /* NO */
1835 case '0': /* 0 */
1836 return 0;
1837 case 't': /* true */
1838 case 'T': /* TRUE */
1839 case 'y': /* yes */
1840 case 'Y': /* YES */
1841 case '1': /* 1 */
1842 return 1;
1843 }
1844 }
1845 return def;
1846}
1847
1848/*
1849 * name is expected to be in the format /type0=value0/type1=value1/type2=...
1850 * where + can be used instead of / to form multi-valued RDNs if canmulti
1851 * and characters may be escaped by \
1852 */
1853X509_NAME *parse_name(const char *cp, int chtype, int canmulti,
1854 const char *desc)
1855{
1856 int nextismulti = 0;
1857 char *work;
1858 X509_NAME *n;
1859
1860 if (*cp++ != '/') {
1861 BIO_printf(bio_err,
1862 "%s: %s name is expected to be in the format "
1863 "/type0=value0/type1=value1/type2=... where characters may "
1864 "be escaped by \\. This name is not in that format: '%s'\n",
1865 opt_getprog(), desc, --cp);
1866 return NULL;
1867 }
1868
1869 n = X509_NAME_new();
1870 if (n == NULL) {
1871 BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog());
1872 return NULL;
1873 }
1874 work = OPENSSL_strdup(cp);
1875 if (work == NULL) {
1876 BIO_printf(bio_err, "%s: Error copying %s name input\n",
1877 opt_getprog(), desc);
1878 goto err;
1879 }
1880
1881 while (*cp != '\0') {
1882 char *bp = work;
1883 char *typestr = bp;
1884 unsigned char *valstr;
1885 int nid;
1886 int ismulti = nextismulti;
1887 nextismulti = 0;
1888
1889 /* Collect the type */
1890 while (*cp != '\0' && *cp != '=')
1891 *bp++ = *cp++;
1892 *bp++ = '\0';
1893 if (*cp == '\0') {
1894 BIO_printf(bio_err,
1895 "%s: Missing '=' after RDN type string '%s' in %s name string\n",
1896 opt_getprog(), typestr, desc);
1897 goto err;
1898 }
1899 ++cp;
1900
1901 /* Collect the value. */
1902 valstr = (unsigned char *)bp;
1903 for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) {
1904 /* unescaped '+' symbol string signals further member of multiRDN */
1905 if (canmulti && *cp == '+') {
1906 nextismulti = 1;
1907 break;
1908 }
1909 if (*cp == '\\' && *++cp == '\0') {
1910 BIO_printf(bio_err,
1911 "%s: Escape character at end of %s name string\n",
1912 opt_getprog(), desc);
1913 goto err;
1914 }
1915 }
1916 *bp++ = '\0';
1917
1918 /* If not at EOS (must be + or /), move forward. */
1919 if (*cp != '\0')
1920 ++cp;
1921
1922 /* Parse */
1923 nid = OBJ_txt2nid(typestr);
1924 if (nid == NID_undef) {
1925 BIO_printf(bio_err,
1926 "%s: Skipping unknown %s name attribute \"%s\"\n",
1927 opt_getprog(), desc, typestr);
1928 if (ismulti)
1929 BIO_printf(bio_err,
1930 "Hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n");
1931 continue;
1932 }
1933 if (*valstr == '\0') {
1934 BIO_printf(bio_err,
1935 "%s: No value provided for %s name attribute \"%s\", skipped\n",
1936 opt_getprog(), desc, typestr);
1937 continue;
1938 }
1939 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1940 valstr, strlen((char *)valstr),
1941 -1, ismulti ? -1 : 0)) {
1942 ERR_print_errors(bio_err);
1943 BIO_printf(bio_err,
1944 "%s: Error adding %s name attribute \"/%s=%s\"\n",
1945 opt_getprog(), desc, typestr ,valstr);
1946 goto err;
1947 }
1948 }
1949
1950 OPENSSL_free(work);
1951 return n;
1952
1953 err:
1954 X509_NAME_free(n);
1955 OPENSSL_free(work);
1956 return NULL;
1957}
1958
1959/*
1960 * Read whole contents of a BIO into an allocated memory buffer and return
1961 * it.
1962 */
1963
1964int bio_to_mem(unsigned char **out, int maxlen, BIO *in)
1965{
1966 BIO *mem;
1967 int len, ret;
1968 unsigned char tbuf[1024];
1969
1970 mem = BIO_new(BIO_s_mem());
1971 if (mem == NULL)
1972 return -1;
1973 for (;;) {
1974 if ((maxlen != -1) && maxlen < 1024)
1975 len = maxlen;
1976 else
1977 len = 1024;
1978 len = BIO_read(in, tbuf, len);
1979 if (len < 0) {
1980 BIO_free(mem);
1981 return -1;
1982 }
1983 if (len == 0)
1984 break;
1985 if (BIO_write(mem, tbuf, len) != len) {
1986 BIO_free(mem);
1987 return -1;
1988 }
1989 maxlen -= len;
1990
1991 if (maxlen == 0)
1992 break;
1993 }
1994 ret = BIO_get_mem_data(mem, (char **)out);
1995 BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY);
1996 BIO_free(mem);
1997 return ret;
1998}
1999
2000int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value)
2001{
2002 int rv = 0;
2003 char *stmp, *vtmp = NULL;
2004
2005 stmp = OPENSSL_strdup(value);
2006 if (stmp == NULL)
2007 return -1;
2008 vtmp = strchr(stmp, ':');
2009 if (vtmp == NULL)
2010 goto err;
2011
2012 *vtmp = 0;
2013 vtmp++;
2014 rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
2015
2016 err:
2017 OPENSSL_free(stmp);
2018 return rv;
2019}
2020
2021static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes)
2022{
2023 X509_POLICY_NODE *node;
2024 int i;
2025
2026 BIO_printf(bio_err, "%s Policies:", name);
2027 if (nodes) {
2028 BIO_puts(bio_err, "\n");
2029 for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) {
2030 node = sk_X509_POLICY_NODE_value(nodes, i);
2031 X509_POLICY_NODE_print(bio_err, node, 2);
2032 }
2033 } else {
2034 BIO_puts(bio_err, " <empty>\n");
2035 }
2036}
2037
2038void policies_print(X509_STORE_CTX *ctx)
2039{
2040 X509_POLICY_TREE *tree;
2041 int explicit_policy;
2042 tree = X509_STORE_CTX_get0_policy_tree(ctx);
2043 explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx);
2044
2045 BIO_printf(bio_err, "Require explicit Policy: %s\n",
2046 explicit_policy ? "True" : "False");
2047
2048 nodes_print("Authority", X509_policy_tree_get0_policies(tree));
2049 nodes_print("User", X509_policy_tree_get0_user_policies(tree));
2050}
2051
2052/*-
2053 * next_protos_parse parses a comma separated list of strings into a string
2054 * in a format suitable for passing to SSL_CTX_set_next_protos_advertised.
2055 * outlen: (output) set to the length of the resulting buffer on success.
2056 * err: (maybe NULL) on failure, an error message line is written to this BIO.
2057 * in: a NUL terminated string like "abc,def,ghi"
2058 *
2059 * returns: a malloc'd buffer or NULL on failure.
2060 */
2061unsigned char *next_protos_parse(size_t *outlen, const char *in)
2062{
2063 size_t len;
2064 unsigned char *out;
2065 size_t i, start = 0;
2066 size_t skipped = 0;
2067
2068 len = strlen(in);
2069 if (len == 0 || len >= 65535)
2070 return NULL;
2071
2072 out = app_malloc(len + 1, "NPN buffer");
2073 for (i = 0; i <= len; ++i) {
2074 if (i == len || in[i] == ',') {
2075 /*
2076 * Zero-length ALPN elements are invalid on the wire, we could be
2077 * strict and reject the entire string, but just ignoring extra
2078 * commas seems harmless and more friendly.
2079 *
2080 * Every comma we skip in this way puts the input buffer another
2081 * byte ahead of the output buffer, so all stores into the output
2082 * buffer need to be decremented by the number commas skipped.
2083 */
2084 if (i == start) {
2085 ++start;
2086 ++skipped;
2087 continue;
2088 }
2089 if (i - start > 255) {
2090 OPENSSL_free(out);
2091 return NULL;
2092 }
2093 out[start-skipped] = (unsigned char)(i - start);
2094 start = i + 1;
2095 } else {
2096 out[i + 1 - skipped] = in[i];
2097 }
2098 }
2099
2100 if (len <= skipped) {
2101 OPENSSL_free(out);
2102 return NULL;
2103 }
2104
2105 *outlen = len + 1 - skipped;
2106 return out;
2107}
2108
2109void print_cert_checks(BIO *bio, X509 *x,
2110 const char *checkhost,
2111 const char *checkemail, const char *checkip)
2112{
2113 if (x == NULL)
2114 return;
2115 if (checkhost) {
2116 BIO_printf(bio, "Hostname %s does%s match certificate\n",
2117 checkhost,
2118 X509_check_host(x, checkhost, 0, 0, NULL) == 1
2119 ? "" : " NOT");
2120 }
2121
2122 if (checkemail) {
2123 BIO_printf(bio, "Email %s does%s match certificate\n",
2124 checkemail, X509_check_email(x, checkemail, 0, 0)
2125 ? "" : " NOT");
2126 }
2127
2128 if (checkip) {
2129 BIO_printf(bio, "IP %s does%s match certificate\n",
2130 checkip, X509_check_ip_asc(x, checkip, 0) ? "" : " NOT");
2131 }
2132}
2133
2134static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
2135{
2136 int i;
2137
2138 if (opts == NULL)
2139 return 1;
2140
2141 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2142 char *opt = sk_OPENSSL_STRING_value(opts, i);
2143 if (pkey_ctrl_string(pkctx, opt) <= 0) {
2144 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2145 ERR_print_errors(bio_err);
2146 return 0;
2147 }
2148 }
2149
2150 return 1;
2151}
2152
2153static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
2154{
2155 int i;
2156
2157 if (opts == NULL)
2158 return 1;
2159
2160 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2161 char *opt = sk_OPENSSL_STRING_value(opts, i);
2162 if (x509_ctrl_string(x, opt) <= 0) {
2163 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2164 ERR_print_errors(bio_err);
2165 return 0;
2166 }
2167 }
2168
2169 return 1;
2170}
2171
2172static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
2173{
2174 int i;
2175
2176 if (opts == NULL)
2177 return 1;
2178
2179 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
2180 char *opt = sk_OPENSSL_STRING_value(opts, i);
2181 if (x509_req_ctrl_string(x, opt) <= 0) {
2182 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
2183 ERR_print_errors(bio_err);
2184 return 0;
2185 }
2186 }
2187
2188 return 1;
2189}
2190
2191static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
2192 const char *md, STACK_OF(OPENSSL_STRING) *sigopts)
2193{
2194 EVP_PKEY_CTX *pkctx = NULL;
2195 char def_md[80];
2196
2197 if (ctx == NULL)
2198 return 0;
2199 /*
2200 * EVP_PKEY_get_default_digest_name() returns 2 if the digest is mandatory
2201 * for this algorithm.
2202 */
2203 if (EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2
2204 && strcmp(def_md, "UNDEF") == 0) {
2205 /* The signing algorithm requires there to be no digest */
2206 md = NULL;
2207 }
2208
2209 return EVP_DigestSignInit_ex(ctx, &pkctx, md, app_get0_libctx(),
2210 app_get0_propq(), pkey, NULL)
2211 && do_pkey_ctx_init(pkctx, sigopts);
2212}
2213
2214static int adapt_keyid_ext(X509 *cert, X509V3_CTX *ext_ctx,
2215 const char *name, const char *value, int add_default)
2216{
2217 const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2218 X509_EXTENSION *new_ext = X509V3_EXT_nconf(NULL, ext_ctx, name, value);
2219 int idx, rv = 0;
2220
2221 if (new_ext == NULL)
2222 return rv;
2223
2224 idx = X509v3_get_ext_by_OBJ(exts, X509_EXTENSION_get_object(new_ext), -1);
2225 if (idx >= 0) {
2226 X509_EXTENSION *found_ext = X509v3_get_ext(exts, idx);
2227 ASN1_OCTET_STRING *data = X509_EXTENSION_get_data(found_ext);
2228 int disabled = ASN1_STRING_length(data) <= 2; /* config said "none" */
2229
2230 if (disabled) {
2231 X509_delete_ext(cert, idx);
2232 X509_EXTENSION_free(found_ext);
2233 } /* else keep existing key identifier, which might be outdated */
2234 rv = 1;
2235 } else {
2236 rv = !add_default || X509_add_ext(cert, new_ext, -1);
2237 }
2238 X509_EXTENSION_free(new_ext);
2239 return rv;
2240}
2241
2242/* Ensure RFC 5280 compliance, adapt keyIDs as needed, and sign the cert info */
2243int do_X509_sign(X509 *cert, EVP_PKEY *pkey, const char *md,
2244 STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx)
2245{
2246 const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert);
2247 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2248 int self_sign;
2249 int rv = 0;
2250
2251 if (sk_X509_EXTENSION_num(exts /* may be NULL */) > 0) {
2252 /* Prevent X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 */
2253 if (!X509_set_version(cert, X509_VERSION_3))
2254 goto end;
2255
2256 /*
2257 * Add default SKID before such that default AKID can make use of it
2258 * in case the certificate is self-signed
2259 */
2260 /* Prevent X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER */
2261 if (!adapt_keyid_ext(cert, ext_ctx, "subjectKeyIdentifier", "hash", 1))
2262 goto end;
2263 /* Prevent X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER */
2264 ERR_set_mark();
2265 self_sign = X509_check_private_key(cert, pkey);
2266 ERR_pop_to_mark();
2267 if (!adapt_keyid_ext(cert, ext_ctx, "authorityKeyIdentifier",
2268 "keyid, issuer", !self_sign))
2269 goto end;
2270 }
2271
2272 if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0)
2273 rv = (X509_sign_ctx(cert, mctx) > 0);
2274 end:
2275 EVP_MD_CTX_free(mctx);
2276 return rv;
2277}
2278
2279/* Sign the certificate request info */
2280int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md,
2281 STACK_OF(OPENSSL_STRING) *sigopts)
2282{
2283 int rv = 0;
2284 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2285
2286 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2287 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
2288 EVP_MD_CTX_free(mctx);
2289 return rv;
2290}
2291
2292/* Sign the CRL info */
2293int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md,
2294 STACK_OF(OPENSSL_STRING) *sigopts)
2295{
2296 int rv = 0;
2297 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
2298
2299 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
2300 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
2301 EVP_MD_CTX_free(mctx);
2302 return rv;
2303}
2304
2305/*
2306 * do_X509_verify returns 1 if the signature is valid,
2307 * 0 if the signature check fails, or -1 if error occurs.
2308 */
2309int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
2310{
2311 int rv = 0;
2312
2313 if (do_x509_init(x, vfyopts) > 0)
2314 rv = X509_verify(x, pkey);
2315 else
2316 rv = -1;
2317 return rv;
2318}
2319
2320/*
2321 * do_X509_REQ_verify returns 1 if the signature is valid,
2322 * 0 if the signature check fails, or -1 if error occurs.
2323 */
2324int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
2325 STACK_OF(OPENSSL_STRING) *vfyopts)
2326{
2327 int rv = 0;
2328
2329 if (do_x509_req_init(x, vfyopts) > 0)
2330 rv = X509_REQ_verify_ex(x, pkey,
2331 app_get0_libctx(), app_get0_propq());
2332 else
2333 rv = -1;
2334 return rv;
2335}
2336
2337/* Get first http URL from a DIST_POINT structure */
2338
2339static const char *get_dp_url(DIST_POINT *dp)
2340{
2341 GENERAL_NAMES *gens;
2342 GENERAL_NAME *gen;
2343 int i, gtype;
2344 ASN1_STRING *uri;
2345 if (!dp->distpoint || dp->distpoint->type != 0)
2346 return NULL;
2347 gens = dp->distpoint->name.fullname;
2348 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
2349 gen = sk_GENERAL_NAME_value(gens, i);
2350 uri = GENERAL_NAME_get0_value(gen, &gtype);
2351 if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) {
2352 const char *uptr = (const char *)ASN1_STRING_get0_data(uri);
2353
2354 if (IS_HTTP(uptr)) /* can/should not use HTTPS here */
2355 return uptr;
2356 }
2357 }
2358 return NULL;
2359}
2360
2361/*
2362 * Look through a CRLDP structure and attempt to find an http URL to
2363 * downloads a CRL from.
2364 */
2365
2366static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp)
2367{
2368 int i;
2369 const char *urlptr = NULL;
2370 for (i = 0; i < sk_DIST_POINT_num(crldp); i++) {
2371 DIST_POINT *dp = sk_DIST_POINT_value(crldp, i);
2372 urlptr = get_dp_url(dp);
2373 if (urlptr != NULL)
2374 return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP");
2375 }
2376 return NULL;
2377}
2378
2379/*
2380 * Example of downloading CRLs from CRLDP:
2381 * not usable for real world as it always downloads and doesn't cache anything.
2382 */
2383
2384static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx,
2385 const X509_NAME *nm)
2386{
2387 X509 *x;
2388 STACK_OF(X509_CRL) *crls = NULL;
2389 X509_CRL *crl;
2390 STACK_OF(DIST_POINT) *crldp;
2391
2392 crls = sk_X509_CRL_new_null();
2393 if (!crls)
2394 return NULL;
2395 x = X509_STORE_CTX_get_current_cert(ctx);
2396 crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
2397 crl = load_crl_crldp(crldp);
2398 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2399 if (!crl) {
2400 sk_X509_CRL_free(crls);
2401 return NULL;
2402 }
2403 sk_X509_CRL_push(crls, crl);
2404 /* Try to download delta CRL */
2405 crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL);
2406 crl = load_crl_crldp(crldp);
2407 sk_DIST_POINT_pop_free(crldp, DIST_POINT_free);
2408 if (crl)
2409 sk_X509_CRL_push(crls, crl);
2410 return crls;
2411}
2412
2413void store_setup_crl_download(X509_STORE *st)
2414{
2415 X509_STORE_set_lookup_crls_cb(st, crls_http_cb);
2416}
2417
2418#ifndef OPENSSL_NO_SOCK
2419static const char *tls_error_hint(void)
2420{
2421 unsigned long err = ERR_peek_error();
2422
2423 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2424 err = ERR_peek_last_error();
2425 if (ERR_GET_LIB(err) != ERR_LIB_SSL)
2426 return NULL;
2427
2428 switch (ERR_GET_REASON(err)) {
2429 case SSL_R_WRONG_VERSION_NUMBER:
2430 return "The server does not support (a suitable version of) TLS";
2431 case SSL_R_UNKNOWN_PROTOCOL:
2432 return "The server does not support HTTPS";
2433 case SSL_R_CERTIFICATE_VERIFY_FAILED:
2434 return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status";
2435 case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA:
2436 return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status";
2437 case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE:
2438 return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it";
2439 default: /* no error or no hint available for error */
2440 return NULL;
2441 }
2442}
2443
2444/* HTTP callback function that supports TLS connection also via HTTPS proxy */
2445BIO *app_http_tls_cb(BIO *hbio, void *arg, int connect, int detail)
2446{
2447 if (connect && detail) { /* connecting with TLS */
2448 APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg;
2449 SSL_CTX *ssl_ctx = info->ssl_ctx;
2450 SSL *ssl;
2451 BIO *sbio = NULL;
2452
2453 if ((info->use_proxy
2454 && !OSSL_HTTP_proxy_connect(hbio, info->server, info->port,
2455 NULL, NULL, /* no proxy credentials */
2456 info->timeout, bio_err, opt_getprog()))
2457 || (sbio = BIO_new(BIO_f_ssl())) == NULL) {
2458 return NULL;
2459 }
2460 if (ssl_ctx == NULL || (ssl = SSL_new(ssl_ctx)) == NULL) {
2461 BIO_free(sbio);
2462 return NULL;
2463 }
2464
2465 SSL_set_tlsext_host_name(ssl, info->server);
2466
2467 SSL_set_connect_state(ssl);
2468 BIO_set_ssl(sbio, ssl, BIO_CLOSE);
2469
2470 hbio = BIO_push(sbio, hbio);
2471 } else if (!connect && !detail) { /* disconnecting after error */
2472 const char *hint = tls_error_hint();
2473
2474 if (hint != NULL)
2475 ERR_add_error_data(2, " : ", hint);
2476 /*
2477 * If we pop sbio and BIO_free() it this may lead to libssl double free.
2478 * Rely on BIO_free_all() done by OSSL_HTTP_transfer() in http_client.c
2479 */
2480 }
2481 return hbio;
2482}
2483
2484void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info)
2485{
2486 if (info != NULL) {
2487 SSL_CTX_free(info->ssl_ctx);
2488 OPENSSL_free(info);
2489 }
2490}
2491
2492ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy,
2493 const char *no_proxy, SSL_CTX *ssl_ctx,
2494 const STACK_OF(CONF_VALUE) *headers,
2495 long timeout, const char *expected_content_type,
2496 const ASN1_ITEM *it)
2497{
2498 APP_HTTP_TLS_INFO info;
2499 char *server;
2500 char *port;
2501 int use_ssl;
2502 BIO *mem;
2503 ASN1_VALUE *resp = NULL;
2504
2505 if (url == NULL || it == NULL) {
2506 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
2507 return NULL;
2508 }
2509
2510 if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL /* userinfo */, &server, &port,
2511 NULL /* port_num, */, NULL, NULL, NULL))
2512 return NULL;
2513 if (use_ssl && ssl_ctx == NULL) {
2514 ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER,
2515 "missing SSL_CTX");
2516 goto end;
2517 }
2518
2519 info.server = server;
2520 info.port = port;
2521 info.use_proxy = proxy != NULL;
2522 info.timeout = timeout;
2523 info.ssl_ctx = ssl_ctx;
2524 mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2525 app_http_tls_cb, &info, 0 /* buf_size */, headers,
2526 expected_content_type, 1 /* expect_asn1 */,
2527 OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout);
2528 resp = ASN1_item_d2i_bio(it, mem, NULL);
2529 BIO_free(mem);
2530
2531 end:
2532 OPENSSL_free(server);
2533 OPENSSL_free(port);
2534 return resp;
2535
2536}
2537
2538ASN1_VALUE *app_http_post_asn1(const char *host, const char *port,
2539 const char *path, const char *proxy,
2540 const char *no_proxy, SSL_CTX *ssl_ctx,
2541 const STACK_OF(CONF_VALUE) *headers,
2542 const char *content_type,
2543 ASN1_VALUE *req, const ASN1_ITEM *req_it,
2544 const char *expected_content_type,
2545 long timeout, const ASN1_ITEM *rsp_it)
2546{
2547 APP_HTTP_TLS_INFO info;
2548 BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req);
2549 ASN1_VALUE *res;
2550
2551 if (req_mem == NULL)
2552 return NULL;
2553 info.server = host;
2554 info.port = port;
2555 info.use_proxy = proxy != NULL;
2556 info.timeout = timeout;
2557 info.ssl_ctx = ssl_ctx;
2558 rsp = OSSL_HTTP_transfer(NULL, host, port, path, ssl_ctx != NULL,
2559 proxy, no_proxy, NULL /* bio */, NULL /* rbio */,
2560 app_http_tls_cb, &info,
2561 0 /* buf_size */, headers, content_type, req_mem,
2562 expected_content_type, 1 /* expect_asn1 */,
2563 OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout,
2564 0 /* keep_alive */);
2565 BIO_free(req_mem);
2566 res = ASN1_item_d2i_bio(rsp_it, rsp, NULL);
2567 BIO_free(rsp);
2568 return res;
2569}
2570
2571#endif
2572
2573/*
2574 * Platform-specific sections
2575 */
2576#if defined(_WIN32)
2577# ifdef fileno
2578# undef fileno
2579# define fileno(a) (int)_fileno(a)
2580# endif
2581
2582# include <windows.h>
2583# include <tchar.h>
2584
2585static int WIN32_rename(const char *from, const char *to)
2586{
2587 TCHAR *tfrom = NULL, *tto;
2588 DWORD err;
2589 int ret = 0;
2590
2591 if (sizeof(TCHAR) == 1) {
2592 tfrom = (TCHAR *)from;
2593 tto = (TCHAR *)to;
2594 } else { /* UNICODE path */
2595
2596 size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1;
2597 tfrom = malloc(sizeof(*tfrom) * (flen + tlen));
2598 if (tfrom == NULL)
2599 goto err;
2600 tto = tfrom + flen;
2601# if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2602 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen))
2603# endif
2604 for (i = 0; i < flen; i++)
2605 tfrom[i] = (TCHAR)from[i];
2606# if !defined(_WIN32_WCE) || _WIN32_WCE>=101
2607 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen))
2608# endif
2609 for (i = 0; i < tlen; i++)
2610 tto[i] = (TCHAR)to[i];
2611 }
2612
2613 if (MoveFile(tfrom, tto))
2614 goto ok;
2615 err = GetLastError();
2616 if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) {
2617 if (DeleteFile(tto) && MoveFile(tfrom, tto))
2618 goto ok;
2619 err = GetLastError();
2620 }
2621 if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
2622 errno = ENOENT;
2623 else if (err == ERROR_ACCESS_DENIED)
2624 errno = EACCES;
2625 else
2626 errno = EINVAL; /* we could map more codes... */
2627 err:
2628 ret = -1;
2629 ok:
2630 if (tfrom != NULL && tfrom != (TCHAR *)from)
2631 free(tfrom);
2632 return ret;
2633}
2634#endif
2635
2636/* app_tminterval section */
2637#if defined(_WIN32)
2638double app_tminterval(int stop, int usertime)
2639{
2640 FILETIME now;
2641 double ret = 0;
2642 static ULARGE_INTEGER tmstart;
2643 static int warning = 1;
2644# ifdef _WIN32_WINNT
2645 static HANDLE proc = NULL;
2646
2647 if (proc == NULL) {
2648 if (check_winnt())
2649 proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
2650 GetCurrentProcessId());
2651 if (proc == NULL)
2652 proc = (HANDLE) - 1;
2653 }
2654
2655 if (usertime && proc != (HANDLE) - 1) {
2656 FILETIME junk;
2657 GetProcessTimes(proc, &junk, &junk, &junk, &now);
2658 } else
2659# endif
2660 {
2661 SYSTEMTIME systime;
2662
2663 if (usertime && warning) {
2664 BIO_printf(bio_err, "To get meaningful results, run "
2665 "this program on idle system.\n");
2666 warning = 0;
2667 }
2668 GetSystemTime(&systime);
2669 SystemTimeToFileTime(&systime, &now);
2670 }
2671
2672 if (stop == TM_START) {
2673 tmstart.u.LowPart = now.dwLowDateTime;
2674 tmstart.u.HighPart = now.dwHighDateTime;
2675 } else {
2676 ULARGE_INTEGER tmstop;
2677
2678 tmstop.u.LowPart = now.dwLowDateTime;
2679 tmstop.u.HighPart = now.dwHighDateTime;
2680
2681 ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7;
2682 }
2683
2684 return ret;
2685}
2686#elif defined(OPENSSL_SYS_VXWORKS)
2687# include <time.h>
2688
2689double app_tminterval(int stop, int usertime)
2690{
2691 double ret = 0;
2692# ifdef CLOCK_REALTIME
2693 static struct timespec tmstart;
2694 struct timespec now;
2695# else
2696 static unsigned long tmstart;
2697 unsigned long now;
2698# endif
2699 static int warning = 1;
2700
2701 if (usertime && warning) {
2702 BIO_printf(bio_err, "To get meaningful results, run "
2703 "this program on idle system.\n");
2704 warning = 0;
2705 }
2706# ifdef CLOCK_REALTIME
2707 clock_gettime(CLOCK_REALTIME, &now);
2708 if (stop == TM_START)
2709 tmstart = now;
2710 else
2711 ret = ((now.tv_sec + now.tv_nsec * 1e-9)
2712 - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9));
2713# else
2714 now = tickGet();
2715 if (stop == TM_START)
2716 tmstart = now;
2717 else
2718 ret = (now - tmstart) / (double)sysClkRateGet();
2719# endif
2720 return ret;
2721}
2722
2723#elif defined(_SC_CLK_TCK) /* by means of unistd.h */
2724# include <sys/times.h>
2725
2726double app_tminterval(int stop, int usertime)
2727{
2728 double ret = 0;
2729 struct tms rus;
2730 clock_t now = times(&rus);
2731 static clock_t tmstart;
2732
2733 if (usertime)
2734 now = rus.tms_utime;
2735
2736 if (stop == TM_START) {
2737 tmstart = now;
2738 } else {
2739 long int tck = sysconf(_SC_CLK_TCK);
2740 ret = (now - tmstart) / (double)tck;
2741 }
2742
2743 return ret;
2744}
2745
2746#else
2747# include <sys/time.h>
2748# include <sys/resource.h>
2749
2750double app_tminterval(int stop, int usertime)
2751{
2752 double ret = 0;
2753 struct rusage rus;
2754 struct timeval now;
2755 static struct timeval tmstart;
2756
2757 if (usertime)
2758 getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime;
2759 else
2760 gettimeofday(&now, NULL);
2761
2762 if (stop == TM_START)
2763 tmstart = now;
2764 else
2765 ret = ((now.tv_sec + now.tv_usec * 1e-6)
2766 - (tmstart.tv_sec + tmstart.tv_usec * 1e-6));
2767
2768 return ret;
2769}
2770#endif
2771
2772int app_access(const char* name, int flag)
2773{
2774#ifdef _WIN32
2775 return _access(name, flag);
2776#else
2777 return access(name, flag);
2778#endif
2779}
2780
2781int app_isdir(const char *name)
2782{
2783 return opt_isdir(name);
2784}
2785
2786/* raw_read|write section */
2787#if defined(__VMS)
2788# include "vms_term_sock.h"
2789static int stdin_sock = -1;
2790
2791static void close_stdin_sock(void)
2792{
2793 TerminalSocket (TERM_SOCK_DELETE, &stdin_sock);
2794}
2795
2796int fileno_stdin(void)
2797{
2798 if (stdin_sock == -1) {
2799 TerminalSocket(TERM_SOCK_CREATE, &stdin_sock);
2800 atexit(close_stdin_sock);
2801 }
2802
2803 return stdin_sock;
2804}
2805#else
2806int fileno_stdin(void)
2807{
2808 return fileno(stdin);
2809}
2810#endif
2811
2812int fileno_stdout(void)
2813{
2814 return fileno(stdout);
2815}
2816
2817#if defined(_WIN32) && defined(STD_INPUT_HANDLE)
2818int raw_read_stdin(void *buf, int siz)
2819{
2820 DWORD n;
2821 if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL))
2822 return n;
2823 else
2824 return -1;
2825}
2826#elif defined(__VMS)
2827# include <sys/socket.h>
2828
2829int raw_read_stdin(void *buf, int siz)
2830{
2831 return recv(fileno_stdin(), buf, siz, 0);
2832}
2833#else
2834# if defined(__TANDEM)
2835# if defined(OPENSSL_TANDEM_FLOSS)
2836# include <floss.h(floss_read)>
2837# endif
2838# endif
2839int raw_read_stdin(void *buf, int siz)
2840{
2841 return read(fileno_stdin(), buf, siz);
2842}
2843#endif
2844
2845#if defined(_WIN32) && defined(STD_OUTPUT_HANDLE)
2846int raw_write_stdout(const void *buf, int siz)
2847{
2848 DWORD n;
2849 if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL))
2850 return n;
2851 else
2852 return -1;
2853}
2854#elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
2855# if defined(__TANDEM)
2856# if defined(OPENSSL_TANDEM_FLOSS)
2857# include <floss.h(floss_write)>
2858# endif
2859# endif
2860int raw_write_stdout(const void *buf,int siz)
2861{
2862 return write(fileno(stdout),(void*)buf,siz);
2863}
2864#else
2865# if defined(__TANDEM)
2866# if defined(OPENSSL_TANDEM_FLOSS)
2867# include <floss.h(floss_write)>
2868# endif
2869# endif
2870int raw_write_stdout(const void *buf, int siz)
2871{
2872 return write(fileno_stdout(), buf, siz);
2873}
2874#endif
2875
2876/*
2877 * Centralized handling of input and output files with format specification
2878 * The format is meant to show what the input and output is supposed to be,
2879 * and is therefore a show of intent more than anything else. However, it
2880 * does impact behavior on some platforms, such as differentiating between
2881 * text and binary input/output on non-Unix platforms
2882 */
2883BIO *dup_bio_in(int format)
2884{
2885 return BIO_new_fp(stdin,
2886 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2887}
2888
2889BIO *dup_bio_out(int format)
2890{
2891 BIO *b = BIO_new_fp(stdout,
2892 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2893 void *prefix = NULL;
2894
2895#ifdef OPENSSL_SYS_VMS
2896 if (FMT_istext(format))
2897 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2898#endif
2899
2900 if (FMT_istext(format)
2901 && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) {
2902 b = BIO_push(BIO_new(BIO_f_prefix()), b);
2903 BIO_set_prefix(b, prefix);
2904 }
2905
2906 return b;
2907}
2908
2909BIO *dup_bio_err(int format)
2910{
2911 BIO *b = BIO_new_fp(stderr,
2912 BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0));
2913#ifdef OPENSSL_SYS_VMS
2914 if (FMT_istext(format))
2915 b = BIO_push(BIO_new(BIO_f_linebuffer()), b);
2916#endif
2917 return b;
2918}
2919
2920void unbuffer(FILE *fp)
2921{
2922/*
2923 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
2924 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
2925 * However, we trust that the C RTL will never give us a FILE pointer
2926 * above the first 4 GB of memory, so we simply turn off the warning
2927 * temporarily.
2928 */
2929#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2930# pragma environment save
2931# pragma message disable maylosedata2
2932#endif
2933 setbuf(fp, NULL);
2934#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
2935# pragma environment restore
2936#endif
2937}
2938
2939static const char *modestr(char mode, int format)
2940{
2941 OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w');
2942
2943 switch (mode) {
2944 case 'a':
2945 return FMT_istext(format) ? "a" : "ab";
2946 case 'r':
2947 return FMT_istext(format) ? "r" : "rb";
2948 case 'w':
2949 return FMT_istext(format) ? "w" : "wb";
2950 }
2951 /* The assert above should make sure we never reach this point */
2952 return NULL;
2953}
2954
2955static const char *modeverb(char mode)
2956{
2957 switch (mode) {
2958 case 'a':
2959 return "appending";
2960 case 'r':
2961 return "reading";
2962 case 'w':
2963 return "writing";
2964 }
2965 return "(doing something)";
2966}
2967
2968/*
2969 * Open a file for writing, owner-read-only.
2970 */
2971BIO *bio_open_owner(const char *filename, int format, int private)
2972{
2973 FILE *fp = NULL;
2974 BIO *b = NULL;
2975 int textmode, bflags;
2976#ifndef OPENSSL_NO_POSIX_IO
2977 int fd = -1, mode;
2978#endif
2979
2980 if (!private || filename == NULL || strcmp(filename, "-") == 0)
2981 return bio_open_default(filename, 'w', format);
2982
2983 textmode = FMT_istext(format);
2984#ifndef OPENSSL_NO_POSIX_IO
2985 mode = O_WRONLY;
2986# ifdef O_CREAT
2987 mode |= O_CREAT;
2988# endif
2989# ifdef O_TRUNC
2990 mode |= O_TRUNC;
2991# endif
2992 if (!textmode) {
2993# ifdef O_BINARY
2994 mode |= O_BINARY;
2995# elif defined(_O_BINARY)
2996 mode |= _O_BINARY;
2997# endif
2998 }
2999
3000# ifdef OPENSSL_SYS_VMS
3001 /* VMS doesn't have O_BINARY, it just doesn't make sense. But,
3002 * it still needs to know that we're going binary, or fdopen()
3003 * will fail with "invalid argument"... so we tell VMS what the
3004 * context is.
3005 */
3006 if (!textmode)
3007 fd = open(filename, mode, 0600, "ctx=bin");
3008 else
3009# endif
3010 fd = open(filename, mode, 0600);
3011 if (fd < 0)
3012 goto err;
3013 fp = fdopen(fd, modestr('w', format));
3014#else /* OPENSSL_NO_POSIX_IO */
3015 /* Have stdio but not Posix IO, do the best we can */
3016 fp = fopen(filename, modestr('w', format));
3017#endif /* OPENSSL_NO_POSIX_IO */
3018 if (fp == NULL)
3019 goto err;
3020 bflags = BIO_CLOSE;
3021 if (textmode)
3022 bflags |= BIO_FP_TEXT;
3023 b = BIO_new_fp(fp, bflags);
3024 if (b != NULL)
3025 return b;
3026
3027 err:
3028 BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n",
3029 opt_getprog(), filename, strerror(errno));
3030 ERR_print_errors(bio_err);
3031 /* If we have fp, then fdopen took over fd, so don't close both. */
3032 if (fp != NULL)
3033 fclose(fp);
3034#ifndef OPENSSL_NO_POSIX_IO
3035 else if (fd >= 0)
3036 close(fd);
3037#endif
3038 return NULL;
3039}
3040
3041static BIO *bio_open_default_(const char *filename, char mode, int format,
3042 int quiet)
3043{
3044 BIO *ret;
3045
3046 if (filename == NULL || strcmp(filename, "-") == 0) {
3047 ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format);
3048 if (quiet) {
3049 ERR_clear_error();
3050 return ret;
3051 }
3052 if (ret != NULL)
3053 return ret;
3054 BIO_printf(bio_err,
3055 "Can't open %s, %s\n",
3056 mode == 'r' ? "stdin" : "stdout", strerror(errno));
3057 } else {
3058 ret = BIO_new_file(filename, modestr(mode, format));
3059 if (quiet) {
3060 ERR_clear_error();
3061 return ret;
3062 }
3063 if (ret != NULL)
3064 return ret;
3065 BIO_printf(bio_err,
3066 "Can't open \"%s\" for %s, %s\n",
3067 filename, modeverb(mode), strerror(errno));
3068 }
3069 ERR_print_errors(bio_err);
3070 return NULL;
3071}
3072
3073BIO *bio_open_default(const char *filename, char mode, int format)
3074{
3075 return bio_open_default_(filename, mode, format, 0);
3076}
3077
3078BIO *bio_open_default_quiet(const char *filename, char mode, int format)
3079{
3080 return bio_open_default_(filename, mode, format, 1);
3081}
3082
3083void wait_for_async(SSL *s)
3084{
3085 /* On Windows select only works for sockets, so we simply don't wait */
3086#ifndef OPENSSL_SYS_WINDOWS
3087 int width = 0;
3088 fd_set asyncfds;
3089 OSSL_ASYNC_FD *fds;
3090 size_t numfds;
3091 size_t i;
3092
3093 if (!SSL_get_all_async_fds(s, NULL, &numfds))
3094 return;
3095 if (numfds == 0)
3096 return;
3097 fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds");
3098 if (!SSL_get_all_async_fds(s, fds, &numfds)) {
3099 OPENSSL_free(fds);
3100 return;
3101 }
3102
3103 FD_ZERO(&asyncfds);
3104 for (i = 0; i < numfds; i++) {
3105 if (width <= (int)fds[i])
3106 width = (int)fds[i] + 1;
3107 openssl_fdset((int)fds[i], &asyncfds);
3108 }
3109 select(width, (void *)&asyncfds, NULL, NULL, NULL);
3110 OPENSSL_free(fds);
3111#endif
3112}
3113
3114/* if OPENSSL_SYS_WINDOWS is defined then so is OPENSSL_SYS_MSDOS */
3115#if defined(OPENSSL_SYS_MSDOS)
3116int has_stdin_waiting(void)
3117{
3118# if defined(OPENSSL_SYS_WINDOWS)
3119 HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE);
3120 DWORD events = 0;
3121 INPUT_RECORD inputrec;
3122 DWORD insize = 1;
3123 BOOL peeked;
3124
3125 if (inhand == INVALID_HANDLE_VALUE) {
3126 return 0;
3127 }
3128
3129 peeked = PeekConsoleInput(inhand, &inputrec, insize, &events);
3130 if (!peeked) {
3131 /* Probably redirected input? _kbhit() does not work in this case */
3132 if (!feof(stdin)) {
3133 return 1;
3134 }
3135 return 0;
3136 }
3137# endif
3138 return _kbhit();
3139}
3140#endif
3141
3142/* Corrupt a signature by modifying final byte */
3143void corrupt_signature(const ASN1_STRING *signature)
3144{
3145 unsigned char *s = signature->data;
3146 s[signature->length - 1] ^= 0x1;
3147}
3148
3149int set_cert_times(X509 *x, const char *startdate, const char *enddate,
3150 int days)
3151{
3152 if (startdate == NULL || strcmp(startdate, "today") == 0) {
3153 if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL)
3154 return 0;
3155 } else {
3156 if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate))
3157 return 0;
3158 }
3159 if (enddate == NULL) {
3160 if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL)
3161 == NULL)
3162 return 0;
3163 } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) {
3164 return 0;
3165 }
3166 return 1;
3167}
3168
3169int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate)
3170{
3171 int ret = 0;
3172 ASN1_TIME *tm = ASN1_TIME_new();
3173
3174 if (tm == NULL)
3175 goto end;
3176
3177 if (lastupdate == NULL) {
3178 if (X509_gmtime_adj(tm, 0) == NULL)
3179 goto end;
3180 } else {
3181 if (!ASN1_TIME_set_string_X509(tm, lastupdate))
3182 goto end;
3183 }
3184
3185 if (!X509_CRL_set1_lastUpdate(crl, tm))
3186 goto end;
3187
3188 ret = 1;
3189end:
3190 ASN1_TIME_free(tm);
3191 return ret;
3192}
3193
3194int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate,
3195 long days, long hours, long secs)
3196{
3197 int ret = 0;
3198 ASN1_TIME *tm = ASN1_TIME_new();
3199
3200 if (tm == NULL)
3201 goto end;
3202
3203 if (nextupdate == NULL) {
3204 if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL)
3205 goto end;
3206 } else {
3207 if (!ASN1_TIME_set_string_X509(tm, nextupdate))
3208 goto end;
3209 }
3210
3211 if (!X509_CRL_set1_nextUpdate(crl, tm))
3212 goto end;
3213
3214 ret = 1;
3215end:
3216 ASN1_TIME_free(tm);
3217 return ret;
3218}
3219
3220void make_uppercase(char *string)
3221{
3222 int i;
3223
3224 for (i = 0; string[i] != '\0'; i++)
3225 string[i] = toupper((unsigned char)string[i]);
3226}
3227
3228/* This function is defined here due to visibility of bio_err */
3229int opt_printf_stderr(const char *fmt, ...)
3230{
3231 va_list ap;
3232 int ret;
3233
3234 va_start(ap, fmt);
3235 ret = BIO_vprintf(bio_err, fmt, ap);
3236 va_end(ap);
3237 return ret;
3238}
3239
3240OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts,
3241 const OSSL_PARAM *paramdefs)
3242{
3243 OSSL_PARAM *params = NULL;
3244 size_t sz = (size_t)sk_OPENSSL_STRING_num(opts);
3245 size_t params_n;
3246 char *opt = "", *stmp, *vtmp = NULL;
3247 int found = 1;
3248
3249 if (opts == NULL)
3250 return NULL;
3251
3252 params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1));
3253 if (params == NULL)
3254 return NULL;
3255
3256 for (params_n = 0; params_n < sz; params_n++) {
3257 opt = sk_OPENSSL_STRING_value(opts, (int)params_n);
3258 if ((stmp = OPENSSL_strdup(opt)) == NULL
3259 || (vtmp = strchr(stmp, ':')) == NULL)
3260 goto err;
3261 /* Replace ':' with 0 to terminate the string pointed to by stmp */
3262 *vtmp = 0;
3263 /* Skip over the separator so that vmtp points to the value */
3264 vtmp++;
3265 if (!OSSL_PARAM_allocate_from_text(&params[params_n], paramdefs,
3266 stmp, vtmp, strlen(vtmp), &found))
3267 goto err;
3268 OPENSSL_free(stmp);
3269 }
3270 params[params_n] = OSSL_PARAM_construct_end();
3271 return params;
3272err:
3273 OPENSSL_free(stmp);
3274 BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown",
3275 opt);
3276 ERR_print_errors(bio_err);
3277 app_params_free(params);
3278 return NULL;
3279}
3280
3281void app_params_free(OSSL_PARAM *params)
3282{
3283 int i;
3284
3285 if (params != NULL) {
3286 for (i = 0; params[i].key != NULL; ++i)
3287 OPENSSL_free(params[i].data);
3288 OPENSSL_free(params);
3289 }
3290}
3291
3292EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose)
3293{
3294 EVP_PKEY *res = NULL;
3295
3296 if (verbose && alg != NULL) {
3297 BIO_printf(bio_err, "Generating %s key", alg);
3298 if (bits > 0)
3299 BIO_printf(bio_err, " with %d bits\n", bits);
3300 else
3301 BIO_printf(bio_err, "\n");
3302 }
3303 if (!RAND_status())
3304 BIO_printf(bio_err, "Warning: generating random key material may take a long time\n"
3305 "if the system has a poor entropy source\n");
3306 if (EVP_PKEY_keygen(ctx, &res) <= 0)
3307 app_bail_out("%s: Error generating %s key\n", opt_getprog(),
3308 alg != NULL ? alg : "asymmetric");
3309 return res;
3310}
3311
3312EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg)
3313{
3314 EVP_PKEY *res = NULL;
3315
3316 if (!RAND_status())
3317 BIO_printf(bio_err, "Warning: generating random key parameters may take a long time\n"
3318 "if the system has a poor entropy source\n");
3319 if (EVP_PKEY_paramgen(ctx, &res) <= 0)
3320 app_bail_out("%s: Generating %s key parameters failed\n",
3321 opt_getprog(), alg != NULL ? alg : "asymmetric");
3322 return res;
3323}
3324
3325/*
3326 * Return non-zero if the legacy path is still an option.
3327 * This decision is based on the global command line operations and the
3328 * behaviour thus far.
3329 */
3330int opt_legacy_okay(void)
3331{
3332 int provider_options = opt_provider_option_given();
3333 int libctx = app_get0_libctx() != NULL || app_get0_propq() != NULL;
3334#ifndef OPENSSL_NO_ENGINE
3335 ENGINE *e = ENGINE_get_first();
3336
3337 if (e != NULL) {
3338 ENGINE_free(e);
3339 return 1;
3340 }
3341#endif
3342 /*
3343 * Having a provider option specified or a custom library context or
3344 * property query, is a sure sign we're not using legacy.
3345 */
3346 if (provider_options || libctx)
3347 return 0;
3348 return 1;
3349}
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette