1 /* $OpenBSD: tls_util.c,v 1.5 2016/11/04 15:59:16 jsing 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
)
102 if ((len
= strlcpy(buf
, u
, size
)) >= (size_t)size
)
109 tls_load_file(const char *name
, size_t *len
, char *password
)
112 EVP_PKEY
*key
= NULL
;
123 if ((fd
= open(name
, O_RDONLY
)) == -1)
126 /* Just load the file into memory without decryption */
127 if (password
== NULL
) {
128 if (fstat(fd
, &st
) != 0)
132 size
= (size_t)st
.st_size
;
133 if ((buf
= malloc(size
)) == NULL
)
135 n
= read(fd
, buf
, size
);
136 if (n
< 0 || (size_t)n
!= size
)
142 /* Or read the (possibly) encrypted key from file */
143 if ((fp
= fdopen(fd
, "r")) == NULL
)
147 key
= PEM_read_PrivateKey(fp
, NULL
, tls_password_cb
, password
);
152 /* Write unencrypted key to memory buffer */
153 if ((bio
= BIO_new(BIO_s_mem())) == NULL
)
155 if (!PEM_write_bio_PrivateKey(bio
, key
, NULL
, NULL
, 0, NULL
, NULL
))
157 if ((size
= BIO_get_mem_data(bio
, &data
)) <= 0)
159 if ((buf
= calloc(1, size
)) == NULL
)
161 memcpy(buf
, data
, size
);