1 /* $OpenBSD: tls_client.c,v 1.48 2021/10/21 08:38:11 tb Exp $ */
3 * Copyright (c) 2014 Joel Sing <jsing@openbsd.org>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 #include <sys/types.h>
19 #include <sys/socket.h>
22 #include <arpa/inet.h>
23 #include <netinet/in.h>
30 #include <openssl/err.h>
31 #include <openssl/x509.h>
34 #include "tls_internal.h"
44 if ((ctx = tls_new()) == NULL)
47 ctx->flags |= TLS_CLIENT;
53 tls_connect(struct tls *ctx, const char *host, const char *port)
55 return tls_connect_servername(ctx, host, port, NULL);
59 tls_connect_servername(struct tls *ctx, const char *host, const char *port,
60 const char *servername)
62 struct addrinfo hints, *res, *res0;
63 const char *h = NULL, *p = NULL;
64 char *hs = NULL, *ps = NULL;
65 int rv = -1, s = -1, ret;
67 if ((ctx->flags & TLS_CLIENT) == 0) {
68 tls_set_errorx(ctx, "not a client context");
73 tls_set_errorx(ctx, "host not specified");
77 /* If port is NULL, try to extract a port from the specified host. */
79 ret = tls_host_port(host, &hs, &ps);
81 tls_set_errorx(ctx, "memory allocation failure");
85 tls_set_errorx(ctx, "no port provided");
90 h = (hs != NULL) ? hs : host;
91 p = (ps != NULL) ? ps : port;
94 * First check if the host is specified as a numeric IP address,
95 * either IPv4 or IPv6, before trying to resolve the host.
96 * The AI_ADDRCONFIG resolver option will not return IPv4 or IPv6
97 * records if it is not configured on an interface; not considering
98 * loopback addresses. Checking the numeric addresses first makes
99 * sure that connection attempts to numeric addresses and especially
100 * 127.0.0.1 or ::1 loopback addresses are always possible.
102 memset(&hints, 0, sizeof(hints));
103 hints.ai_socktype = SOCK_STREAM;
105 /* try as an IPv4 literal */
106 hints.ai_family = AF_INET;
107 hints.ai_flags = AI_NUMERICHOST;
108 if (getaddrinfo(h, p, &hints, &res0) != 0) {
109 /* try again as an IPv6 literal */
110 hints.ai_family = AF_INET6;
111 if (getaddrinfo(h, p, &hints, &res0) != 0) {
112 /* last try, with name resolution and save the error */
113 hints.ai_family = AF_UNSPEC;
114 hints.ai_flags = AI_ADDRCONFIG;
115 if ((s = getaddrinfo(h, p, &hints, &res0)) != 0) {
116 tls_set_error(ctx, "%s", gai_strerror(s));
122 /* It was resolved somehow; now try connecting to what we got */
124 for (res = res0; res; res = res->ai_next) {
125 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
127 tls_set_error(ctx, "socket");
130 if (connect(s, res->ai_addr, res->ai_addrlen) == -1) {
131 tls_set_error(ctx, "connect");
137 break; /* Connected. */
144 if (servername == NULL)
147 if (tls_connect_socket(ctx, s, servername) != 0) {
164 tls_client_read_session(struct tls *ctx)
166 int sfd = ctx->config->session_fd;
167 uint8_t *session = NULL;
168 size_t session_len = 0;
169 SSL_SESSION *ss = NULL;
175 if (fstat(sfd, &sb) == -1) {
176 tls_set_error(ctx, "failed to stat session file");
179 if (sb.st_size < 0 || sb.st_size > INT_MAX) {
180 tls_set_errorx(ctx, "invalid session file size");
183 session_len = (size_t)sb.st_size;
185 /* A zero size file means that we do not yet have a valid session. */
186 if (session_len == 0)
189 if ((session = malloc(session_len)) == NULL)
192 n = pread(sfd, session, session_len, 0);
193 if (n < 0 || (size_t)n != session_len) {
194 tls_set_error(ctx, "failed to read session file");
197 if ((bio = BIO_new_mem_buf(session, session_len)) == NULL)
199 if ((ss = PEM_read_bio_SSL_SESSION(bio, NULL, tls_password_cb,
201 tls_set_errorx(ctx, "failed to parse session");
205 if (SSL_set_session(ctx->ssl_conn, ss) != 1) {
206 tls_set_errorx(ctx, "failed to set session");
214 freezero(session, session_len);
215 SSL_SESSION_free(ss);
222 tls_client_write_session(struct tls *ctx)
224 int sfd = ctx->config->session_fd;
225 SSL_SESSION *ss = NULL;
234 if ((ss = SSL_get1_session(ctx->ssl_conn)) == NULL) {
235 if (ftruncate(sfd, 0) == -1) {
236 tls_set_error(ctx, "failed to truncate session file");
242 if ((bio = BIO_new(BIO_s_mem())) == NULL)
244 if (PEM_write_bio_SSL_SESSION(bio, ss) == 0)
246 if ((data_len = BIO_get_mem_data(bio, &data)) <= 0)
249 len = (size_t)data_len;
252 if (ftruncate(sfd, len) == -1) {
253 tls_set_error(ctx, "failed to truncate session file");
257 if ((n = pwrite(sfd, data + offset, len, offset)) == -1) {
258 tls_set_error(ctx, "failed to write session file");
269 SSL_SESSION_free(ss);
276 tls_connect_common(struct tls *ctx, const char *servername)
278 union tls_addr addrbuf;
279 size_t servername_len;
282 if ((ctx->flags & TLS_CLIENT) == 0) {
283 tls_set_errorx(ctx, "not a client context");
287 if (servername != NULL) {
288 if ((ctx->servername = strdup(servername)) == NULL) {
289 tls_set_errorx(ctx, "out of memory");
294 * If there's a trailing dot, remove it. While an FQDN includes
295 * the terminating dot representing the zero-length label of
296 * the root (RFC 8499, section 2), the SNI explicitly does not
297 * include it (RFC 6066, section 3).
299 servername_len = strlen(ctx->servername);
300 if (servername_len > 0 &&
301 ctx->servername[servername_len - 1] == '.')
302 ctx->servername[servername_len - 1] = '\0';
305 if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
306 tls_set_errorx(ctx, "ssl context failure");
310 if (tls_configure_ssl(ctx, ctx->ssl_ctx) != 0)
313 if (tls_configure_ssl_keypair(ctx, ctx->ssl_ctx,
314 ctx->config->keypair, 0) != 0)
317 if (ctx->config->verify_name) {
318 if (ctx->servername == NULL) {
319 tls_set_errorx(ctx, "server name not specified");
324 if (tls_configure_ssl_verify(ctx, ctx->ssl_ctx, SSL_VERIFY_PEER) == -1)
327 if (ctx->config->ecdhecurves != NULL) {
328 if (SSL_CTX_set1_groups(ctx->ssl_ctx, ctx->config->ecdhecurves,
329 ctx->config->ecdhecurves_len) != 1) {
330 tls_set_errorx(ctx, "failed to set ecdhe curves");
335 if (SSL_CTX_set_tlsext_status_cb(ctx->ssl_ctx, tls_ocsp_verify_cb) != 1) {
336 tls_set_errorx(ctx, "ssl OCSP verification setup failure");
340 if ((ctx->ssl_conn = SSL_new(ctx->ssl_ctx)) == NULL) {
341 tls_set_errorx(ctx, "ssl connection failure");
345 if (SSL_set_app_data(ctx->ssl_conn, ctx) != 1) {
346 tls_set_errorx(ctx, "ssl application data failure");
350 if (ctx->config->session_fd != -1) {
351 SSL_clear_options(ctx->ssl_conn, SSL_OP_NO_TICKET);
352 if (tls_client_read_session(ctx) == -1)
356 if (SSL_set_tlsext_status_type(ctx->ssl_conn, TLSEXT_STATUSTYPE_ocsp) != 1) {
357 tls_set_errorx(ctx, "ssl OCSP extension setup failure");
362 * RFC 6066 (SNI): Literal IPv4 and IPv6 addresses are not
363 * permitted in "HostName".
365 if (ctx->servername != NULL &&
366 inet_pton(AF_INET, ctx->servername, &addrbuf) != 1 &&
367 inet_pton(AF_INET6, ctx->servername, &addrbuf) != 1) {
368 if (SSL_set_tlsext_host_name(ctx->ssl_conn,
369 ctx->servername) == 0) {
370 tls_set_errorx(ctx, "server name indication failure");
375 ctx->state |= TLS_CONNECTED;
383 tls_connect_socket(struct tls *ctx, int s, const char *servername)
385 return tls_connect_fds(ctx, s, s, servername);
389 tls_connect_fds(struct tls *ctx, int fd_read, int fd_write,
390 const char *servername)
394 if (fd_read < 0 || fd_write < 0) {
395 tls_set_errorx(ctx, "invalid file descriptors");
399 if (tls_connect_common(ctx, servername) != 0)
402 if (SSL_set_rfd(ctx->ssl_conn, fd_read) != 1 ||
403 SSL_set_wfd(ctx->ssl_conn, fd_write) != 1) {
404 tls_set_errorx(ctx, "ssl file descriptor failure");
414 tls_connect_cbs(struct tls *ctx, tls_read_cb read_cb,
415 tls_write_cb write_cb, void *cb_arg, const char *servername)
419 if (tls_connect_common(ctx, servername) != 0)
422 if (tls_set_cbs(ctx, read_cb, write_cb, cb_arg) != 0)
432 tls_handshake_client(struct tls *ctx)
438 if ((ctx->flags & TLS_CLIENT) == 0) {
439 tls_set_errorx(ctx, "not a client context");
443 if ((ctx->state & TLS_CONNECTED) == 0) {
444 tls_set_errorx(ctx, "context not connected");
448 ctx->state |= TLS_SSL_NEEDS_SHUTDOWN;
451 if ((ssl_ret = SSL_connect(ctx->ssl_conn)) != 1) {
452 rv = tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "handshake");
456 if (ctx->config->verify_name) {
457 cert = SSL_get_peer_certificate(ctx->ssl_conn);
459 tls_set_errorx(ctx, "no server certificate");
462 if (tls_check_name(ctx, cert, ctx->servername, &match) == -1)
465 tls_set_errorx(ctx, "name `%s' not present in"
466 " server certificate", ctx->servername);
471 ctx->state |= TLS_HANDSHAKE_COMPLETE;
473 if (ctx->config->session_fd != -1) {
474 if (tls_client_write_session(ctx) == -1)