1 /* $OpenBSD: tls_client.c,v 1.51 2024/03/26 08:54:48 joshua 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 <string.h>
29 #include <unistd.h>
30
31 #include <openssl/err.h>
32 #include <openssl/x509.h>
33
34 #include <tls.h>
35 #include "tls_internal.h"
36
37 struct tls *
tls_client(void)38 tls_client(void)
39 {
40 struct tls *ctx;
41
42 if (tls_init() == -1)
43 return (NULL);
44
45 if ((ctx = tls_new()) == NULL)
46 return (NULL);
47
48 ctx->flags |= TLS_CLIENT;
49
50 return (ctx);
51 }
52
53 int
tls_connect(struct tls * ctx,const char * host,const char * port)54 tls_connect(struct tls *ctx, const char *host, const char *port)
55 {
56 return tls_connect_servername(ctx, host, port, NULL);
57 }
58
59 int
tls_connect_servername(struct tls * ctx,const char * host,const char * port,const char * servername)60 tls_connect_servername(struct tls *ctx, const char *host, const char *port,
61 const char *servername)
62 {
63 struct addrinfo hints, *res, *res0;
64 const char *h = NULL, *p = NULL;
65 char *hs = NULL, *ps = NULL;
66 int rv = -1, s = -1, ret;
67
68 if ((ctx->flags & TLS_CLIENT) == 0) {
69 tls_set_errorx(ctx, TLS_ERROR_INVALID_CONTEXT,
70 "not a client context");
71 goto err;
72 }
73
74 if (host == NULL) {
75 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN, "host not specified");
76 goto err;
77 }
78
79 /* If port is NULL, try to extract a port from the specified host. */
80 if (port == NULL) {
81 ret = tls_host_port(host, &hs, &ps);
82 if (ret == -1) {
83 tls_set_errorx(ctx, TLS_ERROR_OUT_OF_MEMORY, "out of memory");
84 goto err;
85 }
86 if (ret != 0) {
87 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN, "no port provided");
88 goto err;
89 }
90 }
91
92 h = (hs != NULL) ? hs : host;
93 p = (ps != NULL) ? ps : port;
94
95 /*
96 * First check if the host is specified as a numeric IP address,
97 * either IPv4 or IPv6, before trying to resolve the host.
98 * The AI_ADDRCONFIG resolver option will not return IPv4 or IPv6
99 * records if it is not configured on an interface; not considering
100 * loopback addresses. Checking the numeric addresses first makes
101 * sure that connection attempts to numeric addresses and especially
102 * 127.0.0.1 or ::1 loopback addresses are always possible.
103 */
104 memset(&hints, 0, sizeof(hints));
105 hints.ai_socktype = SOCK_STREAM;
106
107 /* try as an IPv4 literal */
108 hints.ai_family = AF_INET;
109 hints.ai_flags = AI_NUMERICHOST;
110 if (getaddrinfo(h, p, &hints, &res0) != 0) {
111 /* try again as an IPv6 literal */
112 hints.ai_family = AF_INET6;
113 if (getaddrinfo(h, p, &hints, &res0) != 0) {
114 /* last try, with name resolution and save the error */
115 hints.ai_family = AF_UNSPEC;
116 hints.ai_flags = AI_ADDRCONFIG;
117 if ((s = getaddrinfo(h, p, &hints, &res0)) != 0) {
118 tls_set_error(ctx, TLS_ERROR_UNKNOWN,
119 "%s", gai_strerror(s));
120 goto err;
121 }
122 }
123 }
124
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, TLS_ERROR_UNKNOWN,
131 "socket");
132 continue;
133 }
134 if (connect(s, res->ai_addr, res->ai_addrlen) == -1) {
135 tls_set_error(ctx, TLS_ERROR_UNKNOWN,
136 "connect");
137 close(s);
138 s = -1;
139 continue;
140 }
141
142 break; /* Connected. */
143 }
144 freeaddrinfo(res0);
145
146 if (s == -1)
147 goto err;
148
149 if (servername == NULL)
150 servername = h;
151
152 if (tls_connect_socket(ctx, s, servername) != 0) {
153 close(s);
154 goto err;
155 }
156
157 ctx->socket = s;
158
159 rv = 0;
160
161 err:
162 free(hs);
163 free(ps);
164
165 return (rv);
166 }
167
168 static int
tls_client_read_session(struct tls * ctx)169 tls_client_read_session(struct tls *ctx)
170 {
171 int sfd = ctx->config->session_fd;
172 uint8_t *session = NULL;
173 size_t session_len = 0;
174 SSL_SESSION *ss = NULL;
175 BIO *bio = NULL;
176 struct stat sb;
177 ssize_t n;
178 int rv = -1;
179
180 if (fstat(sfd, &sb) == -1) {
181 tls_set_error(ctx, TLS_ERROR_UNKNOWN,
182 "failed to stat session file");
183 goto err;
184 }
185 if (sb.st_size < 0 || sb.st_size > INT_MAX) {
186 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
187 "invalid session file size");
188 goto err;
189 }
190 session_len = (size_t)sb.st_size;
191
192 /* A zero size file means that we do not yet have a valid session. */
193 if (session_len == 0)
194 goto done;
195
196 if ((session = malloc(session_len)) == NULL)
197 goto err;
198
199 n = pread(sfd, session, session_len, 0);
200 if (n < 0 || (size_t)n != session_len) {
201 tls_set_error(ctx, TLS_ERROR_UNKNOWN,
202 "failed to read session file");
203 goto err;
204 }
205 if ((bio = BIO_new_mem_buf(session, session_len)) == NULL)
206 goto err;
207 if ((ss = PEM_read_bio_SSL_SESSION(bio, NULL, tls_password_cb,
208 NULL)) == NULL) {
209 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
210 "failed to parse session");
211 goto err;
212 }
213
214 if (SSL_set_session(ctx->ssl_conn, ss) != 1) {
215 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
216 "failed to set session");
217 goto err;
218 }
219
220 done:
221 rv = 0;
222
223 err:
224 freezero(session, session_len);
225 SSL_SESSION_free(ss);
226 BIO_free(bio);
227
228 return rv;
229 }
230
231 static int
tls_client_write_session(struct tls * ctx)232 tls_client_write_session(struct tls *ctx)
233 {
234 int sfd = ctx->config->session_fd;
235 SSL_SESSION *ss = NULL;
236 BIO *bio = NULL;
237 long data_len;
238 char *data;
239 off_t offset;
240 size_t len;
241 ssize_t n;
242 int rv = -1;
243
244 if ((ss = SSL_get1_session(ctx->ssl_conn)) == NULL) {
245 if (ftruncate(sfd, 0) == -1) {
246 tls_set_error(ctx, TLS_ERROR_UNKNOWN,
247 "failed to truncate session file");
248 goto err;
249 }
250 goto done;
251 }
252
253 if ((bio = BIO_new(BIO_s_mem())) == NULL)
254 goto err;
255 if (PEM_write_bio_SSL_SESSION(bio, ss) == 0)
256 goto err;
257 if ((data_len = BIO_get_mem_data(bio, &data)) <= 0)
258 goto err;
259
260 len = (size_t)data_len;
261 offset = 0;
262
263 if (ftruncate(sfd, len) == -1) {
264 tls_set_error(ctx, TLS_ERROR_UNKNOWN,
265 "failed to truncate session file");
266 goto err;
267 }
268 while (len > 0) {
269 if ((n = pwrite(sfd, data + offset, len, offset)) == -1) {
270 tls_set_error(ctx, TLS_ERROR_UNKNOWN,
271 "failed to write session file");
272 goto err;
273 }
274 offset += n;
275 len -= n;
276 }
277
278 done:
279 rv = 0;
280
281 err:
282 SSL_SESSION_free(ss);
283 BIO_free_all(bio);
284
285 return (rv);
286 }
287
288 static int
tls_connect_common(struct tls * ctx,const char * servername)289 tls_connect_common(struct tls *ctx, const char *servername)
290 {
291 union tls_addr addrbuf;
292 size_t servername_len;
293 int rv = -1;
294
295 if ((ctx->flags & TLS_CLIENT) == 0) {
296 tls_set_errorx(ctx, TLS_ERROR_INVALID_CONTEXT,
297 "not a client context");
298 goto err;
299 }
300
301 if (servername != NULL) {
302 if ((ctx->servername = strdup(servername)) == NULL) {
303 tls_set_errorx(ctx, TLS_ERROR_OUT_OF_MEMORY,
304 "out of memory");
305 goto err;
306 }
307
308 /*
309 * If there's a trailing dot, remove it. While an FQDN includes
310 * the terminating dot representing the zero-length label of
311 * the root (RFC 8499, section 2), the SNI explicitly does not
312 * include it (RFC 6066, section 3).
313 */
314 servername_len = strlen(ctx->servername);
315 if (servername_len > 0 &&
316 ctx->servername[servername_len - 1] == '.')
317 ctx->servername[servername_len - 1] = '\0';
318 }
319
320 if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
321 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN, "ssl context failure");
322 goto err;
323 }
324
325 if (tls_configure_ssl(ctx, ctx->ssl_ctx) != 0)
326 goto err;
327
328 if (tls_configure_ssl_keypair(ctx, ctx->ssl_ctx,
329 ctx->config->keypair, 0) != 0)
330 goto err;
331
332 if (ctx->config->verify_name) {
333 if (ctx->servername == NULL) {
334 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
335 "server name not specified");
336 goto err;
337 }
338 }
339
340 if (tls_configure_ssl_verify(ctx, ctx->ssl_ctx, SSL_VERIFY_PEER) == -1)
341 goto err;
342
343 if (ctx->config->ecdhecurves != NULL) {
344 if (SSL_CTX_set1_groups(ctx->ssl_ctx, ctx->config->ecdhecurves,
345 ctx->config->ecdhecurves_len) != 1) {
346 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
347 "failed to set ecdhe curves");
348 goto err;
349 }
350 }
351
352 if (SSL_CTX_set_tlsext_status_cb(ctx->ssl_ctx, tls_ocsp_verify_cb) != 1) {
353 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
354 "ssl OCSP verification setup failure");
355 goto err;
356 }
357
358 if ((ctx->ssl_conn = SSL_new(ctx->ssl_ctx)) == NULL) {
359 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN, "ssl connection failure");
360 goto err;
361 }
362
363 if (SSL_set_app_data(ctx->ssl_conn, ctx) != 1) {
364 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
365 "ssl application data failure");
366 goto err;
367 }
368
369 if (ctx->config->session_fd != -1) {
370 SSL_clear_options(ctx->ssl_conn, SSL_OP_NO_TICKET);
371 if (tls_client_read_session(ctx) == -1)
372 goto err;
373 }
374
375 if (SSL_set_tlsext_status_type(ctx->ssl_conn, TLSEXT_STATUSTYPE_ocsp) != 1) {
376 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
377 "ssl OCSP extension setup failure");
378 goto err;
379 }
380
381 /*
382 * RFC 6066 (SNI): Literal IPv4 and IPv6 addresses are not
383 * permitted in "HostName".
384 */
385 if (ctx->servername != NULL &&
386 inet_pton(AF_INET, ctx->servername, &addrbuf) != 1 &&
387 inet_pton(AF_INET6, ctx->servername, &addrbuf) != 1) {
388 if (SSL_set_tlsext_host_name(ctx->ssl_conn,
389 ctx->servername) == 0) {
390 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
391 "server name indication failure");
392 goto err;
393 }
394 }
395
396 ctx->state |= TLS_CONNECTED;
397 rv = 0;
398
399 err:
400 return (rv);
401 }
402
403 int
tls_connect_socket(struct tls * ctx,int s,const char * servername)404 tls_connect_socket(struct tls *ctx, int s, const char *servername)
405 {
406 return tls_connect_fds(ctx, s, s, servername);
407 }
408
409 int
tls_connect_fds(struct tls * ctx,int fd_read,int fd_write,const char * servername)410 tls_connect_fds(struct tls *ctx, int fd_read, int fd_write,
411 const char *servername)
412 {
413 int rv = -1;
414
415 if (fd_read < 0 || fd_write < 0) {
416 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN, "invalid file descriptors");
417 goto err;
418 }
419
420 if (tls_connect_common(ctx, servername) != 0)
421 goto err;
422
423 if (SSL_set_rfd(ctx->ssl_conn, fd_read) != 1 ||
424 SSL_set_wfd(ctx->ssl_conn, fd_write) != 1) {
425 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
426 "ssl file descriptor failure");
427 goto err;
428 }
429
430 rv = 0;
431 err:
432 return (rv);
433 }
434
435 int
tls_connect_cbs(struct tls * ctx,tls_read_cb read_cb,tls_write_cb write_cb,void * cb_arg,const char * servername)436 tls_connect_cbs(struct tls *ctx, tls_read_cb read_cb,
437 tls_write_cb write_cb, void *cb_arg, const char *servername)
438 {
439 int rv = -1;
440
441 if (tls_connect_common(ctx, servername) != 0)
442 goto err;
443
444 if (tls_set_cbs(ctx, read_cb, write_cb, cb_arg) != 0)
445 goto err;
446
447 rv = 0;
448
449 err:
450 return (rv);
451 }
452
453 int
tls_handshake_client(struct tls * ctx)454 tls_handshake_client(struct tls *ctx)
455 {
456 X509 *cert = NULL;
457 int match, ssl_ret;
458 int rv = -1;
459
460 if ((ctx->flags & TLS_CLIENT) == 0) {
461 tls_set_errorx(ctx, TLS_ERROR_INVALID_CONTEXT,
462 "not a client context");
463 goto err;
464 }
465
466 if ((ctx->state & TLS_CONNECTED) == 0) {
467 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN, "context not connected");
468 goto err;
469 }
470
471 ctx->state |= TLS_SSL_NEEDS_SHUTDOWN;
472
473 ERR_clear_error();
474 if ((ssl_ret = SSL_connect(ctx->ssl_conn)) != 1) {
475 rv = tls_ssl_error(ctx, ctx->ssl_conn, ssl_ret, "handshake");
476 goto err;
477 }
478
479 if (ctx->config->verify_name) {
480 cert = SSL_get_peer_certificate(ctx->ssl_conn);
481 if (cert == NULL) {
482 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
483 "no server certificate");
484 goto err;
485 }
486 if (tls_check_name(ctx, cert, ctx->servername, &match) == -1)
487 goto err;
488 if (!match) {
489 tls_set_errorx(ctx, TLS_ERROR_UNKNOWN,
490 "name `%s' not present in server certificate",
491 ctx->servername);
492 goto err;
493 }
494 }
495
496 ctx->state |= TLS_HANDSHAKE_COMPLETE;
497
498 if (ctx->config->session_fd != -1) {
499 if (tls_client_write_session(ctx) == -1)
500 goto err;
501 }
502
503 rv = 0;
504
505 err:
506 X509_free(cert);
507
508 return (rv);
509 }
510