xref: /openbsd-src/lib/libtls/tls_client.c (revision 6c6408334dbede3a2c0dcd9ff9c489157df0c856)
1 /* $OpenBSD: tls_client.c,v 1.44 2018/02/10 04:41:24 jsing 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 ((ctx = tls_new()) == NULL)
42 		return (NULL);
43 
44 	ctx->flags |= TLS_CLIENT;
45 
46 	return (ctx);
47 }
48 
49 int
50 tls_connect(struct tls *ctx, const char *host, const char *port)
51 {
52 	return tls_connect_servername(ctx, host, port, NULL);
53 }
54 
55 int
56 tls_connect_servername(struct tls *ctx, const char *host, const char *port,
57     const char *servername)
58 {
59 	struct addrinfo hints, *res, *res0;
60 	const char *h = NULL, *p = NULL;
61 	char *hs = NULL, *ps = NULL;
62 	int rv = -1, s = -1, ret;
63 
64 	if ((ctx->flags & TLS_CLIENT) == 0) {
65 		tls_set_errorx(ctx, "not a client context");
66 		goto err;
67 	}
68 
69 	if (host == NULL) {
70 		tls_set_errorx(ctx, "host not specified");
71 		goto err;
72 	}
73 
74 	/*
75 	 * If port is NULL try to extract a port from the specified host,
76 	 * otherwise use the default.
77 	 */
78 	if ((p = (char *)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 	int rv = -1;
280 
281 	if ((ctx->flags & TLS_CLIENT) == 0) {
282 		tls_set_errorx(ctx, "not a client context");
283 		goto err;
284 	}
285 
286 	if (servername != NULL) {
287 		if ((ctx->servername = strdup(servername)) == NULL) {
288 			tls_set_errorx(ctx, "out of memory");
289 			goto err;
290 		}
291 	}
292 
293 	if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
294 		tls_set_errorx(ctx, "ssl context failure");
295 		goto err;
296 	}
297 
298 	if (tls_configure_ssl(ctx, ctx->ssl_ctx) != 0)
299 		goto err;
300 
301 	if (tls_configure_ssl_keypair(ctx, ctx->ssl_ctx,
302 	    ctx->config->keypair, 0) != 0)
303 		goto err;
304 
305 	if (ctx->config->verify_name) {
306 		if (servername == NULL) {
307 			tls_set_errorx(ctx, "server name not specified");
308 			goto err;
309 		}
310 	}
311 
312 	if (tls_configure_ssl_verify(ctx, ctx->ssl_ctx, SSL_VERIFY_PEER) == -1)
313 		goto err;
314 
315 	if (ctx->config->ecdhecurves != NULL) {
316 		if (SSL_CTX_set1_groups(ctx->ssl_ctx, ctx->config->ecdhecurves,
317 		    ctx->config->ecdhecurves_len) != 1) {
318 			tls_set_errorx(ctx, "failed to set ecdhe curves");
319 			goto err;
320 		}
321 	}
322 
323 	if (SSL_CTX_set_tlsext_status_cb(ctx->ssl_ctx, tls_ocsp_verify_cb) != 1) {
324 		tls_set_errorx(ctx, "ssl OCSP verification setup failure");
325 		goto err;
326 	}
327 
328 	if ((ctx->ssl_conn = SSL_new(ctx->ssl_ctx)) == NULL) {
329 		tls_set_errorx(ctx, "ssl connection failure");
330 		goto err;
331 	}
332 
333 	if (SSL_set_app_data(ctx->ssl_conn, ctx) != 1) {
334 		tls_set_errorx(ctx, "ssl application data failure");
335 		goto err;
336 	}
337 
338 	if (ctx->config->session_fd != -1) {
339 		SSL_clear_options(ctx->ssl_conn, SSL_OP_NO_TICKET);
340 		if (tls_client_read_session(ctx) == -1)
341 			goto err;
342 	}
343 
344 	if (SSL_set_tlsext_status_type(ctx->ssl_conn, TLSEXT_STATUSTYPE_ocsp) != 1) {
345 		tls_set_errorx(ctx, "ssl OCSP extension setup failure");
346 		goto err;
347 	}
348 
349 	/*
350 	 * RFC4366 (SNI): Literal IPv4 and IPv6 addresses are not
351 	 * permitted in "HostName".
352 	 */
353 	if (servername != NULL &&
354 	    inet_pton(AF_INET, servername, &addrbuf) != 1 &&
355 	    inet_pton(AF_INET6, servername, &addrbuf) != 1) {
356 		if (SSL_set_tlsext_host_name(ctx->ssl_conn, servername) == 0) {
357 			tls_set_errorx(ctx, "server name indication failure");
358 			goto err;
359 		}
360 	}
361 
362 	ctx->state |= TLS_CONNECTED;
363 	rv = 0;
364 
365  err:
366 	return (rv);
367 }
368 
369 int
370 tls_connect_socket(struct tls *ctx, int s, const char *servername)
371 {
372 	return tls_connect_fds(ctx, s, s, servername);
373 }
374 
375 int
376 tls_connect_fds(struct tls *ctx, int fd_read, int fd_write,
377     const char *servername)
378 {
379 	int rv = -1;
380 
381 	if (fd_read < 0 || fd_write < 0) {
382 		tls_set_errorx(ctx, "invalid file descriptors");
383 		goto err;
384 	}
385 
386 	if (tls_connect_common(ctx, servername) != 0)
387 		goto err;
388 
389 	if (SSL_set_rfd(ctx->ssl_conn, fd_read) != 1 ||
390 	    SSL_set_wfd(ctx->ssl_conn, fd_write) != 1) {
391 		tls_set_errorx(ctx, "ssl file descriptor failure");
392 		goto err;
393 	}
394 
395 	rv = 0;
396  err:
397 	return (rv);
398 }
399 
400 int
401 tls_connect_cbs(struct tls *ctx, tls_read_cb read_cb,
402     tls_write_cb write_cb, void *cb_arg, const char *servername)
403 {
404 	int rv = -1;
405 
406 	if (tls_connect_common(ctx, servername) != 0)
407 		goto err;
408 
409 	if (tls_set_cbs(ctx, read_cb, write_cb, cb_arg) != 0)
410 		goto err;
411 
412 	rv = 0;
413 
414  err:
415 	return (rv);
416 }
417 
418 int
419 tls_handshake_client(struct tls *ctx)
420 {
421 	X509 *cert = NULL;
422 	int match, ssl_ret;
423 	int rv = -1;
424 
425 	if ((ctx->flags & TLS_CLIENT) == 0) {
426 		tls_set_errorx(ctx, "not a client context");
427 		goto err;
428 	}
429 
430 	if ((ctx->state & TLS_CONNECTED) == 0) {
431 		tls_set_errorx(ctx, "context not connected");
432 		goto err;
433 	}
434 
435 	ctx->state |= TLS_SSL_NEEDS_SHUTDOWN;
436 
437 	ERR_clear_error();
438 	if ((ssl_ret = SSL_connect(ctx->ssl_conn)) != 1) {
439 		rv = tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "handshake");
440 		goto err;
441 	}
442 
443 	if (ctx->config->verify_name) {
444 		cert = SSL_get_peer_certificate(ctx->ssl_conn);
445 		if (cert == NULL) {
446 			tls_set_errorx(ctx, "no server certificate");
447 			goto err;
448 		}
449 		if (tls_check_name(ctx, cert, ctx->servername, &match) == -1)
450 			goto err;
451 		if (!match) {
452 			tls_set_errorx(ctx, "name `%s' not present in"
453 			    " server certificate", ctx->servername);
454 			goto err;
455 		}
456 	}
457 
458 	ctx->state |= TLS_HANDSHAKE_COMPLETE;
459 
460 	if (ctx->config->session_fd != -1) {
461 		if (tls_client_write_session(ctx) == -1)
462 			goto err;
463 	}
464 
465 	rv = 0;
466 
467  err:
468 	X509_free(cert);
469 
470 	return (rv);
471 }
472