VirtualBox

source: vbox/trunk/src/libs/openssl-3.1.7/apps/lib/apps.c@ 106683

Last change on this file since 106683 was 104078, checked in by vboxsync, 12 months ago

openssl-3.1.5: Applied and adjusted our OpenSSL changes to 3.1.4. bugref:10638

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