1 /* $OpenBSD: tls_util.c,v 1.2 2015/02/07 23:25:37 reyk Exp $ */
3 * Copyright (c) 2014 Joel Sing <jsing@openbsd.org>
4 * Copyright (c) 2015 Reyk Floeter <reyk@openbsd.org>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26 #include "tls_internal.h"
29 * Extract the host and port from a colon separated value. For a literal IPv6
30 * address the address must be contained with square braces. If a host and
31 * port are successfully extracted, the function will return 0 and the
32 * caller is responsible for freeing the host and port. If no port is found
33 * then the function will return 1, with both host and port being NULL.
34 * On memory allocation failure -1 will be returned.
37 tls_host_port(const char *hostport, char **host, char **port)
45 if ((s = strdup(hostport)) == NULL)
50 /* See if this is an IPv6 literal with square braces. */
53 if ((p = strchr(s, ']')) == NULL)
58 /* Find the port seperator. */
59 if ((p = strchr(p, ':')) == NULL)
62 /* If there is another separator then we have issues. */
63 if (strchr(p + 1, ':') != NULL)
68 if (asprintf(host, "%s", h) == -1)
70 if (asprintf(port, "%s", p) == -1)
90 tls_password_cb(char *buf, int size, int rwflag, void *u)
97 if ((len = strlcpy(buf, u, size)) >= (size_t)size)
103 tls_load_file(const char *name, size_t *len, char *password)
106 EVP_PKEY *key = NULL;
108 char *data, *buf = NULL;
115 if ((fd = open(name, O_RDONLY)) == -1)
118 /* Just load the file into memory without decryption */
119 if (password == NULL) {
120 if (fstat(fd, &st) != 0)
122 size = (size_t)st.st_size;
123 if ((buf = calloc(1, size + 1)) == NULL)
125 if (read(fd, buf, size) != size)
131 /* Or read the (possibly) encrypted key from file */
132 if ((fp = fdopen(fd, "r")) == NULL)
136 key = PEM_read_PrivateKey(fp, NULL, tls_password_cb, password);
141 /* Write unencrypted key to memory buffer */
142 if ((bio = BIO_new(BIO_s_mem())) == NULL)
144 if (!PEM_write_bio_PrivateKey(bio, key, NULL, NULL, 0, NULL, NULL))
146 if ((size = BIO_get_mem_data(bio, &data)) <= 0)
148 if ((buf = calloc(1, size)) == NULL)
150 memcpy(buf, data, size);