xref: /dragonfly/crypto/libressl/tls/tls_client.c (revision 6f5ec8b5)
1 /* $OpenBSD: tls_client.c,v 1.48 2021/10/21 08:38:11 tb 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  */
17 
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <sys/stat.h>
21 
22 #include <arpa/inet.h>
23 #include <netinet/in.h>
24 
25 #include <limits.h>
26 #include <netdb.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 
30 #include <openssl/err.h>
31 #include <openssl/x509.h>
32 
33 #include <tls.h>
34 #include "tls_internal.h"
35 
36 struct tls *
37 tls_client(void)
38 {
39 	struct tls *ctx;
40 
41 	if (tls_init() == -1)
42 		return (NULL);
43 
44 	if ((ctx = tls_new()) == NULL)
45 		return (NULL);
46 
47 	ctx->flags |= TLS_CLIENT;
48 
49 	return (ctx);
50 }
51 
52 int
53 tls_connect(struct tls *ctx, const char *host, const char *port)
54 {
55 	return tls_connect_servername(ctx, host, port, NULL);
56 }
57 
58 int
59 tls_connect_servername(struct tls *ctx, const char *host, const char *port,
60     const char *servername)
61 {
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;
66 
67 	if ((ctx->flags & TLS_CLIENT) == 0) {
68 		tls_set_errorx(ctx, "not a client context");
69 		goto err;
70 	}
71 
72 	if (host == NULL) {
73 		tls_set_errorx(ctx, "host not specified");
74 		goto err;
75 	}
76 
77 	/* If port is NULL, try to extract a port from the specified host. */
78 	if (port == NULL) {
79 		ret = tls_host_port(host, &hs, &ps);
80 		if (ret == -1) {
81 			tls_set_errorx(ctx, "memory allocation failure");
82 			goto err;
83 		}
84 		if (ret != 0) {
85 			tls_set_errorx(ctx, "no port provided");
86 			goto err;
87 		}
88 	}
89 
90 	h = (hs != NULL) ? hs : host;
91 	p = (ps != NULL) ? ps : port;
92 
93 	/*
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.
101 	 */
102 	memset(&hints, 0, sizeof(hints));
103 	hints.ai_socktype = SOCK_STREAM;
104 
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));
117 				goto err;
118 			}
119 		}
120 	}
121 
122 	/* It was resolved somehow; now try connecting to what we got */
123 	s = -1;
124 	for (res = res0; res; res = res->ai_next) {
125 		s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
126 		if (s == -1) {
127 			tls_set_error(ctx, "socket");
128 			continue;
129 		}
130 		if (connect(s, res->ai_addr, res->ai_addrlen) == -1) {
131 			tls_set_error(ctx, "connect");
132 			close(s);
133 			s = -1;
134 			continue;
135 		}
136 
137 		break;  /* Connected. */
138 	}
139 	freeaddrinfo(res0);
140 
141 	if (s == -1)
142 		goto err;
143 
144 	if (servername == NULL)
145 		servername = h;
146 
147 	if (tls_connect_socket(ctx, s, servername) != 0) {
148 		close(s);
149 		goto err;
150 	}
151 
152 	ctx->socket = s;
153 
154 	rv = 0;
155 
156  err:
157 	free(hs);
158 	free(ps);
159 
160 	return (rv);
161 }
162 
163 static int
164 tls_client_read_session(struct tls *ctx)
165 {
166 	int sfd = ctx->config->session_fd;
167 	uint8_t *session = NULL;
168 	size_t session_len = 0;
169 	SSL_SESSION *ss = NULL;
170 	BIO *bio = NULL;
171 	struct stat sb;
172 	ssize_t n;
173 	int rv = -1;
174 
175 	if (fstat(sfd, &sb) == -1) {
176 		tls_set_error(ctx, "failed to stat session file");
177 		goto err;
178 	}
179 	if (sb.st_size < 0 || sb.st_size > INT_MAX) {
180 		tls_set_errorx(ctx, "invalid session file size");
181 		goto err;
182 	}
183 	session_len = (size_t)sb.st_size;
184 
185 	/* A zero size file means that we do not yet have a valid session. */
186 	if (session_len == 0)
187 		goto done;
188 
189 	if ((session = malloc(session_len)) == NULL)
190 		goto err;
191 
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");
195 		goto err;
196 	}
197 	if ((bio = BIO_new_mem_buf(session, session_len)) == NULL)
198 		goto err;
199 	if ((ss = PEM_read_bio_SSL_SESSION(bio, NULL, tls_password_cb,
200 	    NULL)) == NULL) {
201 		tls_set_errorx(ctx, "failed to parse session");
202 		goto err;
203 	}
204 
205 	if (SSL_set_session(ctx->ssl_conn, ss) != 1) {
206 		tls_set_errorx(ctx, "failed to set session");
207 		goto err;
208 	}
209 
210  done:
211 	rv = 0;
212 
213  err:
214 	freezero(session, session_len);
215 	SSL_SESSION_free(ss);
216 	BIO_free(bio);
217 
218 	return rv;
219 }
220 
221 static int
222 tls_client_write_session(struct tls *ctx)
223 {
224 	int sfd = ctx->config->session_fd;
225 	SSL_SESSION *ss = NULL;
226 	BIO *bio = NULL;
227 	long data_len;
228 	char *data;
229 	off_t offset;
230 	size_t len;
231 	ssize_t n;
232 	int rv = -1;
233 
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");
237 			goto err;
238 		}
239 		goto done;
240 	}
241 
242 	if ((bio = BIO_new(BIO_s_mem())) == NULL)
243 		goto err;
244 	if (PEM_write_bio_SSL_SESSION(bio, ss) == 0)
245 		goto err;
246 	if ((data_len = BIO_get_mem_data(bio, &data)) <= 0)
247 		goto err;
248 
249 	len = (size_t)data_len;
250 	offset = 0;
251 
252 	if (ftruncate(sfd, len) == -1) {
253 		tls_set_error(ctx, "failed to truncate session file");
254 		goto err;
255 	}
256 	while (len > 0) {
257 		if ((n = pwrite(sfd, data + offset, len, offset)) == -1) {
258 			tls_set_error(ctx, "failed to write session file");
259 			goto err;
260 		}
261 		offset += n;
262 		len -= n;
263 	}
264 
265  done:
266 	rv = 0;
267 
268  err:
269 	SSL_SESSION_free(ss);
270 	BIO_free_all(bio);
271 
272 	return (rv);
273 }
274 
275 static int
276 tls_connect_common(struct tls *ctx, const char *servername)
277 {
278 	union tls_addr addrbuf;
279 	size_t servername_len;
280 	int rv = -1;
281 
282 	if ((ctx->flags & TLS_CLIENT) == 0) {
283 		tls_set_errorx(ctx, "not a client context");
284 		goto err;
285 	}
286 
287 	if (servername != NULL) {
288 		if ((ctx->servername = strdup(servername)) == NULL) {
289 			tls_set_errorx(ctx, "out of memory");
290 			goto err;
291 		}
292 
293 		/*
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).
298 		 */
299 		servername_len = strlen(ctx->servername);
300 		if (servername_len > 0 &&
301 		    ctx->servername[servername_len - 1] == '.')
302 			ctx->servername[servername_len - 1] = '\0';
303 	}
304 
305 	if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
306 		tls_set_errorx(ctx, "ssl context failure");
307 		goto err;
308 	}
309 
310 	if (tls_configure_ssl(ctx, ctx->ssl_ctx) != 0)
311 		goto err;
312 
313 	if (tls_configure_ssl_keypair(ctx, ctx->ssl_ctx,
314 	    ctx->config->keypair, 0) != 0)
315 		goto err;
316 
317 	if (ctx->config->verify_name) {
318 		if (ctx->servername == NULL) {
319 			tls_set_errorx(ctx, "server name not specified");
320 			goto err;
321 		}
322 	}
323 
324 	if (tls_configure_ssl_verify(ctx, ctx->ssl_ctx, SSL_VERIFY_PEER) == -1)
325 		goto err;
326 
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");
331 			goto err;
332 		}
333 	}
334 
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");
337 		goto err;
338 	}
339 
340 	if ((ctx->ssl_conn = SSL_new(ctx->ssl_ctx)) == NULL) {
341 		tls_set_errorx(ctx, "ssl connection failure");
342 		goto err;
343 	}
344 
345 	if (SSL_set_app_data(ctx->ssl_conn, ctx) != 1) {
346 		tls_set_errorx(ctx, "ssl application data failure");
347 		goto err;
348 	}
349 
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)
353 			goto err;
354 	}
355 
356 	if (SSL_set_tlsext_status_type(ctx->ssl_conn, TLSEXT_STATUSTYPE_ocsp) != 1) {
357 		tls_set_errorx(ctx, "ssl OCSP extension setup failure");
358 		goto err;
359 	}
360 
361 	/*
362 	 * RFC 6066 (SNI): Literal IPv4 and IPv6 addresses are not
363 	 * permitted in "HostName".
364 	 */
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");
371 			goto err;
372 		}
373 	}
374 
375 	ctx->state |= TLS_CONNECTED;
376 	rv = 0;
377 
378  err:
379 	return (rv);
380 }
381 
382 int
383 tls_connect_socket(struct tls *ctx, int s, const char *servername)
384 {
385 	return tls_connect_fds(ctx, s, s, servername);
386 }
387 
388 int
389 tls_connect_fds(struct tls *ctx, int fd_read, int fd_write,
390     const char *servername)
391 {
392 	int rv = -1;
393 
394 	if (fd_read < 0 || fd_write < 0) {
395 		tls_set_errorx(ctx, "invalid file descriptors");
396 		goto err;
397 	}
398 
399 	if (tls_connect_common(ctx, servername) != 0)
400 		goto err;
401 
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");
405 		goto err;
406 	}
407 
408 	rv = 0;
409  err:
410 	return (rv);
411 }
412 
413 int
414 tls_connect_cbs(struct tls *ctx, tls_read_cb read_cb,
415     tls_write_cb write_cb, void *cb_arg, const char *servername)
416 {
417 	int rv = -1;
418 
419 	if (tls_connect_common(ctx, servername) != 0)
420 		goto err;
421 
422 	if (tls_set_cbs(ctx, read_cb, write_cb, cb_arg) != 0)
423 		goto err;
424 
425 	rv = 0;
426 
427  err:
428 	return (rv);
429 }
430 
431 int
432 tls_handshake_client(struct tls *ctx)
433 {
434 	X509 *cert = NULL;
435 	int match, ssl_ret;
436 	int rv = -1;
437 
438 	if ((ctx->flags & TLS_CLIENT) == 0) {
439 		tls_set_errorx(ctx, "not a client context");
440 		goto err;
441 	}
442 
443 	if ((ctx->state & TLS_CONNECTED) == 0) {
444 		tls_set_errorx(ctx, "context not connected");
445 		goto err;
446 	}
447 
448 	ctx->state |= TLS_SSL_NEEDS_SHUTDOWN;
449 
450 	ERR_clear_error();
451 	if ((ssl_ret = SSL_connect(ctx->ssl_conn)) != 1) {
452 		rv = tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "handshake");
453 		goto err;
454 	}
455 
456 	if (ctx->config->verify_name) {
457 		cert = SSL_get_peer_certificate(ctx->ssl_conn);
458 		if (cert == NULL) {
459 			tls_set_errorx(ctx, "no server certificate");
460 			goto err;
461 		}
462 		if (tls_check_name(ctx, cert, ctx->servername, &match) == -1)
463 			goto err;
464 		if (!match) {
465 			tls_set_errorx(ctx, "name `%s' not present in"
466 			    " server certificate", ctx->servername);
467 			goto err;
468 		}
469 	}
470 
471 	ctx->state |= TLS_HANDSHAKE_COMPLETE;
472 
473 	if (ctx->config->session_fd != -1) {
474 		if (tls_client_write_session(ctx) == -1)
475 			goto err;
476 	}
477 
478 	rv = 0;
479 
480  err:
481 	X509_free(cert);
482 
483 	return (rv);
484 }
485