Blob


1 /* $OpenBSD: tls_client.c,v 1.49 2023/05/14 07:26:25 op Exp $ */
2 /*
3 * Copyright (c) 2014 Joel Sing <jsing@openbsd.org>
4 *
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.
8 *
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.
16 */
18 #include "config.h"
20 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <sys/stat.h>
24 #include <arpa/inet.h>
25 #include <netinet/in.h>
27 #include <limits.h>
28 #include <netdb.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
33 #include <openssl/err.h>
34 #include <openssl/x509.h>
36 #include <tls.h>
37 #include "tls_internal.h"
39 struct tls *
40 tls_client(void)
41 {
42 struct tls *ctx;
44 if (tls_init() == -1)
45 return (NULL);
47 if ((ctx = tls_new()) == NULL)
48 return (NULL);
50 ctx->flags |= TLS_CLIENT;
52 return (ctx);
53 }
55 int
56 tls_connect(struct tls *ctx, const char *host, const char *port)
57 {
58 return tls_connect_servername(ctx, host, port, NULL);
59 }
61 int
62 tls_connect_servername(struct tls *ctx, const char *host, const char *port,
63 const char *servername)
64 {
65 struct addrinfo hints, *res, *res0;
66 const char *h = NULL, *p = NULL;
67 char *hs = NULL, *ps = NULL;
68 int rv = -1, s = -1, ret;
70 if ((ctx->flags & TLS_CLIENT) == 0) {
71 tls_set_errorx(ctx, "not a client context");
72 goto err;
73 }
75 if (host == NULL) {
76 tls_set_errorx(ctx, "host not specified");
77 goto err;
78 }
80 /* If port is NULL, try to extract a port from the specified host. */
81 if (port == NULL) {
82 ret = tls_host_port(host, &hs, &ps);
83 if (ret == -1) {
84 tls_set_errorx(ctx, "memory allocation failure");
85 goto err;
86 }
87 if (ret != 0) {
88 tls_set_errorx(ctx, "no port provided");
89 goto err;
90 }
91 }
93 h = (hs != NULL) ? hs : host;
94 p = (ps != NULL) ? ps : port;
96 /*
97 * First check if the host is specified as a numeric IP address,
98 * either IPv4 or IPv6, before trying to resolve the host.
99 * The AI_ADDRCONFIG resolver option will not return IPv4 or IPv6
100 * records if it is not configured on an interface; not considering
101 * loopback addresses. Checking the numeric addresses first makes
102 * sure that connection attempts to numeric addresses and especially
103 * 127.0.0.1 or ::1 loopback addresses are always possible.
104 */
105 memset(&hints, 0, sizeof(hints));
106 hints.ai_socktype = SOCK_STREAM;
108 /* try as an IPv4 literal */
109 hints.ai_family = AF_INET;
110 hints.ai_flags = AI_NUMERICHOST;
111 if (getaddrinfo(h, p, &hints, &res0) != 0) {
112 /* try again as an IPv6 literal */
113 hints.ai_family = AF_INET6;
114 if (getaddrinfo(h, p, &hints, &res0) != 0) {
115 /* last try, with name resolution and save the error */
116 hints.ai_family = AF_UNSPEC;
117 hints.ai_flags = AI_ADDRCONFIG;
118 if ((s = getaddrinfo(h, p, &hints, &res0)) != 0) {
119 tls_set_error(ctx, "%s", gai_strerror(s));
120 goto err;
125 /* It was resolved somehow; now try connecting to what we got */
126 s = -1;
127 for (res = res0; res; res = res->ai_next) {
128 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
129 if (s == -1) {
130 tls_set_error(ctx, "socket");
131 continue;
133 if (connect(s, res->ai_addr, res->ai_addrlen) == -1) {
134 tls_set_error(ctx, "connect");
135 close(s);
136 s = -1;
137 continue;
140 break; /* Connected. */
142 freeaddrinfo(res0);
144 if (s == -1)
145 goto err;
147 if (servername == NULL)
148 servername = h;
150 if (tls_connect_socket(ctx, s, servername) != 0) {
151 close(s);
152 goto err;
155 ctx->socket = s;
157 rv = 0;
159 err:
160 free(hs);
161 free(ps);
163 return (rv);
166 static int
167 tls_client_read_session(struct tls *ctx)
169 int sfd = ctx->config->session_fd;
170 uint8_t *session = NULL;
171 size_t session_len = 0;
172 SSL_SESSION *ss = NULL;
173 BIO *bio = NULL;
174 struct stat sb;
175 ssize_t n;
176 int rv = -1;
178 if (fstat(sfd, &sb) == -1) {
179 tls_set_error(ctx, "failed to stat session file");
180 goto err;
182 if (sb.st_size < 0 || sb.st_size > INT_MAX) {
183 tls_set_errorx(ctx, "invalid session file size");
184 goto err;
186 session_len = (size_t)sb.st_size;
188 /* A zero size file means that we do not yet have a valid session. */
189 if (session_len == 0)
190 goto done;
192 if ((session = malloc(session_len)) == NULL)
193 goto err;
195 n = pread(sfd, session, session_len, 0);
196 if (n < 0 || (size_t)n != session_len) {
197 tls_set_error(ctx, "failed to read session file");
198 goto err;
200 if ((bio = BIO_new_mem_buf(session, session_len)) == NULL)
201 goto err;
202 if ((ss = PEM_read_bio_SSL_SESSION(bio, NULL, tls_password_cb,
203 NULL)) == NULL) {
204 tls_set_errorx(ctx, "failed to parse session");
205 goto err;
208 if (SSL_set_session(ctx->ssl_conn, ss) != 1) {
209 tls_set_errorx(ctx, "failed to set session");
210 goto err;
213 done:
214 rv = 0;
216 err:
217 freezero(session, session_len);
218 SSL_SESSION_free(ss);
219 BIO_free(bio);
221 return rv;
224 static int
225 tls_client_write_session(struct tls *ctx)
227 int sfd = ctx->config->session_fd;
228 SSL_SESSION *ss = NULL;
229 BIO *bio = NULL;
230 long data_len;
231 char *data;
232 off_t offset;
233 size_t len;
234 ssize_t n;
235 int rv = -1;
237 if ((ss = SSL_get1_session(ctx->ssl_conn)) == NULL) {
238 if (ftruncate(sfd, 0) == -1) {
239 tls_set_error(ctx, "failed to truncate session file");
240 goto err;
242 goto done;
245 if ((bio = BIO_new(BIO_s_mem())) == NULL)
246 goto err;
247 if (PEM_write_bio_SSL_SESSION(bio, ss) == 0)
248 goto err;
249 if ((data_len = BIO_get_mem_data(bio, &data)) <= 0)
250 goto err;
252 len = (size_t)data_len;
253 offset = 0;
255 if (ftruncate(sfd, len) == -1) {
256 tls_set_error(ctx, "failed to truncate session file");
257 goto err;
259 while (len > 0) {
260 if ((n = pwrite(sfd, data + offset, len, offset)) == -1) {
261 tls_set_error(ctx, "failed to write session file");
262 goto err;
264 offset += n;
265 len -= n;
268 done:
269 rv = 0;
271 err:
272 SSL_SESSION_free(ss);
273 BIO_free_all(bio);
275 return (rv);
278 static int
279 tls_connect_common(struct tls *ctx, const char *servername)
281 union tls_addr addrbuf;
282 size_t servername_len;
283 int rv = -1;
285 if ((ctx->flags & TLS_CLIENT) == 0) {
286 tls_set_errorx(ctx, "not a client context");
287 goto err;
290 if (servername != NULL) {
291 if ((ctx->servername = strdup(servername)) == NULL) {
292 tls_set_errorx(ctx, "out of memory");
293 goto err;
296 /*
297 * If there's a trailing dot, remove it. While an FQDN includes
298 * the terminating dot representing the zero-length label of
299 * the root (RFC 8499, section 2), the SNI explicitly does not
300 * include it (RFC 6066, section 3).
301 */
302 servername_len = strlen(ctx->servername);
303 if (servername_len > 0 &&
304 ctx->servername[servername_len - 1] == '.')
305 ctx->servername[servername_len - 1] = '\0';
308 if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
309 tls_set_errorx(ctx, "ssl context failure");
310 goto err;
313 if (tls_configure_ssl(ctx, ctx->ssl_ctx) != 0)
314 goto err;
316 if (tls_configure_ssl_keypair(ctx, ctx->ssl_ctx,
317 ctx->config->keypair, 0) != 0)
318 goto err;
320 if (ctx->config->verify_name) {
321 if (ctx->servername == NULL) {
322 tls_set_errorx(ctx, "server name not specified");
323 goto err;
327 if (tls_configure_ssl_verify(ctx, ctx->ssl_ctx, SSL_VERIFY_PEER) == -1)
328 goto err;
330 if (ctx->config->ecdhecurves != NULL) {
331 if (SSL_CTX_set1_groups(ctx->ssl_ctx, ctx->config->ecdhecurves,
332 ctx->config->ecdhecurves_len) != 1) {
333 tls_set_errorx(ctx, "failed to set ecdhe curves");
334 goto err;
338 if (SSL_CTX_set_tlsext_status_cb(ctx->ssl_ctx, tls_ocsp_verify_cb) != 1) {
339 tls_set_errorx(ctx, "ssl OCSP verification setup failure");
340 goto err;
343 if ((ctx->ssl_conn = SSL_new(ctx->ssl_ctx)) == NULL) {
344 tls_set_errorx(ctx, "ssl connection failure");
345 goto err;
348 if (SSL_set_app_data(ctx->ssl_conn, ctx) != 1) {
349 tls_set_errorx(ctx, "ssl application data failure");
350 goto err;
353 if (ctx->config->session_fd != -1) {
354 SSL_clear_options(ctx->ssl_conn, SSL_OP_NO_TICKET);
355 if (tls_client_read_session(ctx) == -1)
356 goto err;
359 if (SSL_set_tlsext_status_type(ctx->ssl_conn, TLSEXT_STATUSTYPE_ocsp) != 1) {
360 tls_set_errorx(ctx, "ssl OCSP extension setup failure");
361 goto err;
364 /*
365 * RFC 6066 (SNI): Literal IPv4 and IPv6 addresses are not
366 * permitted in "HostName".
367 */
368 if (ctx->servername != NULL &&
369 inet_pton(AF_INET, ctx->servername, &addrbuf) != 1 &&
370 inet_pton(AF_INET6, ctx->servername, &addrbuf) != 1) {
371 if (SSL_set_tlsext_host_name(ctx->ssl_conn,
372 ctx->servername) == 0) {
373 tls_set_errorx(ctx, "server name indication failure");
374 goto err;
378 ctx->state |= TLS_CONNECTED;
379 rv = 0;
381 err:
382 return (rv);
385 int
386 tls_connect_socket(struct tls *ctx, int s, const char *servername)
388 return tls_connect_fds(ctx, s, s, servername);
391 int
392 tls_connect_fds(struct tls *ctx, int fd_read, int fd_write,
393 const char *servername)
395 int rv = -1;
397 if (fd_read < 0 || fd_write < 0) {
398 tls_set_errorx(ctx, "invalid file descriptors");
399 goto err;
402 if (tls_connect_common(ctx, servername) != 0)
403 goto err;
405 if (SSL_set_rfd(ctx->ssl_conn, fd_read) != 1 ||
406 SSL_set_wfd(ctx->ssl_conn, fd_write) != 1) {
407 tls_set_errorx(ctx, "ssl file descriptor failure");
408 goto err;
411 rv = 0;
412 err:
413 return (rv);
416 int
417 tls_connect_cbs(struct tls *ctx, tls_read_cb read_cb,
418 tls_write_cb write_cb, void *cb_arg, const char *servername)
420 int rv = -1;
422 if (tls_connect_common(ctx, servername) != 0)
423 goto err;
425 if (tls_set_cbs(ctx, read_cb, write_cb, cb_arg) != 0)
426 goto err;
428 rv = 0;
430 err:
431 return (rv);
434 int
435 tls_handshake_client(struct tls *ctx)
437 X509 *cert = NULL;
438 int match, ssl_ret;
439 int rv = -1;
441 if ((ctx->flags & TLS_CLIENT) == 0) {
442 tls_set_errorx(ctx, "not a client context");
443 goto err;
446 if ((ctx->state & TLS_CONNECTED) == 0) {
447 tls_set_errorx(ctx, "context not connected");
448 goto err;
451 ctx->state |= TLS_SSL_NEEDS_SHUTDOWN;
453 ERR_clear_error();
454 if ((ssl_ret = SSL_connect(ctx->ssl_conn)) != 1) {
455 rv = tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "handshake");
456 goto err;
459 if (ctx->config->verify_name) {
460 cert = SSL_get_peer_certificate(ctx->ssl_conn);
461 if (cert == NULL) {
462 tls_set_errorx(ctx, "no server certificate");
463 goto err;
465 if (tls_check_name(ctx, cert, ctx->servername, &match) == -1)
466 goto err;
467 if (!match) {
468 tls_set_errorx(ctx, "name `%s' not present in"
469 " server certificate", ctx->servername);
470 goto err;
474 ctx->state |= TLS_HANDSHAKE_COMPLETE;
476 if (ctx->config->session_fd != -1) {
477 if (tls_client_write_session(ctx) == -1)
478 goto err;
481 rv = 0;
483 err:
484 X509_free(cert);
486 return (rv);