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