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