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