Debian Codegraph @

src/tls/connection.c

raw
1 /*
2 * Copyright (C) 2019 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 #include "config.h"
7
8 #include "connection.h"
9
10 #include <arpa/inet.h>
11 #include <assert.h>
12 #include <err.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <net/if.h>
16 #include <netinet/in.h>
17 #include <poll.h>
18 #include <pthread.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <sys/epoll.h>
23 #include <sys/param.h>
24 #include <sys/socket.h>
25 #include <sys/stat.h>
26 #include <sys/timerfd.h>
27 #include <sys/types.h>
28 #include <sys/uio.h>
29 #include <unistd.h>
30
31 #include <gnutls/gnutls.h>
32 #include <gnutls/x509.h>
33
34 #include <common/cockpitfdpassing.h>
35 #include <common/cockpitjsonprint.h>
36 #include <common/cockpitmemory.h>
37 #include <common/cockpitwebcertificate.h>
38
39 #include "credentials.h"
40 #include "client-certificate.h"
41 #include "httpredirect.h"
42 #include "socket-io.h"
43 #include "utils.h"
44
45 /* cockpit-tls TCP server state (singleton) */
46 static struct {
47 gnutls_certificate_request_t request_mode;
48 Credentials *credentials;
49 bool require_https;
50 int wsinstance_sockdir;
51 int cert_session_dir;
52 } parameters = {
53 .wsinstance_sockdir = -1,
54 .cert_session_dir = -1
55 };
56
57 typedef struct
58 {
59 char buffer[16u << 10]; /* 16KiB */
60 unsigned start, end;
61 bool eof, shut_rd, shut_wr;
62 #ifdef DEBUG
63 const char *name;
64 #endif
65 } Buffer;
66
67 /* a single TCP connection between the client (browser) and cockpit-tls */
68 typedef struct {
69 int client_fd;
70 int ws_fd;
71
72 gnutls_session_t tls;
73
74 Buffer client_to_ws_buffer;
75 Buffer ws_to_client_buffer;
76
77 char *client_cert_filename;
78 char *wsinstance;
79 int metadata_fd;
80 } Connection;
81
82 #define BUFFER_SIZE (sizeof ((Buffer *) 0)->buffer)
83 #define BUFFER_MASK (BUFFER_SIZE - 1)
84
85 static_assert (!(BUFFER_SIZE & BUFFER_MASK), "buffer size not a power of 2");
86 static_assert ((typeof (((Buffer *) 0)->start)) BUFFER_SIZE, "buffer is too big");
87
88
89 static inline bool
90 buffer_full (Buffer *self)
91 {
92 return self->end - self->start == BUFFER_SIZE;
93 }
94
95 static inline bool
96 buffer_empty (Buffer *self)
97 {
98 return self->end == self->start;
99 }
100
101 static inline bool
102 buffer_can_read (Buffer *self)
103 {
104 return !self->shut_rd && !buffer_full (self);
105 }
106
107 static inline bool
108 buffer_can_write (Buffer *self)
109 {
110 return !self->shut_wr && !buffer_empty (self);
111 }
112
113 static inline bool
114 buffer_needs_shut_rd (Buffer *self)
115 {
116 return self->eof && !self->shut_rd;
117 }
118
119 static inline bool
120 buffer_needs_shut_wr (Buffer *self)
121 {
122 return self->eof && buffer_empty (self) && !self->shut_wr;
123 }
124
125 static inline bool
126 buffer_alive (Buffer *self)
127 {
128 return !self->shut_rd || !self->shut_wr;
129 }
130
131 static void
132 buffer_shut_rd (Buffer *self)
133 {
134 self->shut_rd = true;
135 }
136
137 static void
138 buffer_shut_wr (Buffer *self)
139 {
140 self->shut_wr = true;
141 }
142
143 static void
144 buffer_eof (Buffer *self)
145 {
146 self->eof = true;
147 }
148
149 static void
150 buffer_epipe (Buffer *self)
151 {
152 self->start = self->end;
153 self->eof = true;
154 }
155
156 static inline bool
157 buffer_valid (Buffer *self)
158 {
159 return self->end - self->start <= BUFFER_SIZE;
160 }
161
162 static short
163 calculate_events (Buffer *reader,
164 Buffer *writer)
165 {
166 return buffer_can_read (reader) * POLLIN | buffer_can_write (writer) * POLLOUT;
167 }
168
169 static short
170 calculate_revents (Buffer *reader,
171 Buffer *writer)
172 {
173 return buffer_needs_shut_rd (reader) * POLLIN | buffer_needs_shut_wr (writer) * POLLOUT;
174 }
175
176 static int
177 get_iovecs (struct iovec *iov,
178 int iov_length,
179 char *buffer,
180 unsigned start,
181 unsigned end)
182 {
183 int i = 0;
184
185 debug (IOVEC, " get_iovecs (%p, %i, %p, 0x%x, 0x%x)", iov, iov_length, buffer, start, end);
186 assert (end - start <= BUFFER_SIZE);
187
188 for (i = 0; i < iov_length && start != end; i++)
189 {
190 unsigned start_offset = start & BUFFER_MASK;
191
192 iov[i].iov_base = &buffer[start_offset];
193 iov[i].iov_len = MIN(BUFFER_SIZE - start_offset, end - start);
194 start += iov[i].iov_len;
195
196 debug (IOVEC, " iov[%i] = { 0x%zx, 0x%zx }; start = 0x%x;", i,
197 ((char *) iov[i].iov_base - buffer), iov[i].iov_len, start);
198 }
199
200 debug (IOVEC, " return %i;", i);
201
202 return i;
203 }
204
205 static void
206 buffer_write_to_fd (Buffer *self,
207 int fd,
208 int *fd_to_send)
209 {
210 struct iovec iov[2];
211 ssize_t s;
212
213 debug (BUFFER, "buffer_write_to_fd (%s/0x%x/0x%x, %i)", self->name, self->start, self->end, fd);
214
215 struct msghdr msg = { .msg_iov = iov };
216 msg.msg_iovlen = get_iovecs (iov, 2, self->buffer, self->start, self->end);
217
218 if (msg.msg_iovlen)
219 {
220 struct cmsghdr cmsg[2];
221
222 if (fd_to_send && *fd_to_send != -1)
223 cockpit_socket_msghdr_add_fd (&msg, cmsg, sizeof cmsg, *fd_to_send);
224
225 do
226 s = sendmsg (fd, &msg, MSG_NOSIGNAL | MSG_DONTWAIT);
227 while (s == -1 && errno == EINTR);
228
229 debug (BUFFER, " sendmsg returns %zi %s", s, (s == -1) ? strerror (errno) : "");
230
231 if (fd_to_send && *fd_to_send != -1 && s != -1)
232 {
233 close (*fd_to_send);
234 *fd_to_send = -1;
235 }
236
237 if (s == -1)
238 {
239 if (errno != EAGAIN)
240 /* Includes the expected case of EPIPE */
241 buffer_epipe (self);
242 }
243 else
244 self->start += s;
245 }
246
247 if (buffer_needs_shut_wr (self))
248 {
249 shutdown (fd, SHUT_WR);
250 buffer_shut_wr (self);
251 }
252
253 assert (buffer_valid (self));
254 }
255
256 static void
257 buffer_read_from_fd (Buffer *self,
258 int fd)
259 {
260 debug (BUFFER, "buffer_read_from_fd (%s/0x%x/0x%x, %i)", self->name, self->start, self->end, fd);
261
262 if (buffer_needs_shut_rd (self))
263 {
264 shutdown (fd, SHUT_RD);
265 buffer_shut_rd (self);
266 return;
267 }
268
269 struct iovec iov[2];
270 ssize_t s;
271 int iovcnt = get_iovecs (iov, 2, self->buffer, self->end, self->start + BUFFER_SIZE);
272 assert (iovcnt > 0);
273
274 do
275 s = readv (fd, iov, iovcnt);
276 while (s == -1 && errno == EINTR);
277
278 debug (BUFFER, " readv returns %zi %s", s, (s == -1) ? strerror (errno) : "");
279
280 if (s == -1)
281 {
282 if (errno != EAGAIN)
283 buffer_eof (self);
284 }
285 else if (s == 0)
286 buffer_eof (self);
287 else
288 self->end += s;
289
290 assert (buffer_valid (self));
291 }
292
293 static void
294 buffer_write_to_tls (Buffer *self,
295 gnutls_session_t tls)
296 {
297 struct iovec iov;
298 ssize_t s;
299
300 debug (BUFFER, "buffer_write_to_tls (%s/0x%x/0x%x, %p)", self->name, self->start, self->end, tls);
301
302 if (get_iovecs (&iov, 1, self->buffer, self->start, self->end))
303 {
304 do
305 s = gnutls_record_send (tls, iov.iov_base, iov.iov_len);
306 while (s == GNUTLS_E_INTERRUPTED);
307
308 debug (BUFFER, " gnutls_record_send returns %zi %s", s, (s < 0) ? gnutls_strerror (-s) : "");
309
310 if (s < 0)
311 {
312 if (s != GNUTLS_E_AGAIN)
313 buffer_epipe (self);
314 }
315 else
316 self->start += s;
317 }
318
319 if (buffer_needs_shut_wr (self))
320 {
321 gnutls_bye (tls, GNUTLS_SHUT_WR);
322 buffer_shut_wr (self);
323 }
324
325 assert (buffer_valid (self));
326 }
327
328 static void
329 buffer_read_from_tls (Buffer *self,
330 gnutls_session_t tls)
331 {
332 struct iovec iov;
333 ssize_t s;
334
335 debug (BUFFER, "buffer_read_from_tls (%s/0x%x/0x%x, %p)", self->name, self->start, self->end, tls);
336
337 if (buffer_needs_shut_rd (self))
338 {
339 /* There's not GNUTLS_SHUT_RD, so do the shutdown() on the
340 * underlying fd.
341 */
342 shutdown (gnutls_transport_get_int (tls), SHUT_RD);
343 buffer_shut_rd (self);
344 return;
345 }
346
347 int iovcnt = get_iovecs (&iov, 1, self->buffer, self->end, self->start + BUFFER_SIZE);
348 assert (iovcnt == 1);
349
350 do
351 s = gnutls_record_recv (tls, iov.iov_base, iov.iov_len);
352 while (s == GNUTLS_E_INTERRUPTED);
353
354 debug (BUFFER, " gnutls_record_recv returns %zi %s", s, (s < 0) ? gnutls_strerror (-s) : "");
355
356 if (s <= 0)
357 {
358 if (s != GNUTLS_E_AGAIN)
359 buffer_epipe (self);
360 }
361 else
362 self->end += s;
363
364 assert (buffer_valid (self));
365 }
366
367 static bool
368 request_dynamic_wsinstance (const char *fingerprint)
369 {
370 bool status = false;
371 char reply[20];
372
373 debug (CONNECTION, "requesting dynamic wsinstance for %s:\n", fingerprint);
374
375 int fd = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
376 if (fd == -1)
377 {
378 warn ("socket() failed");
379 goto out;
380 }
381
382 debug (CONNECTION, " -> connecting to https-factory.sock");
383 if (af_unix_connectat (fd, parameters.wsinstance_sockdir, "https-factory.sock") != 0)
384 {
385 warn ("connect(https-factory.sock) failed");
386 goto out;
387 }
388
389 /* send the fingerprint */
390 debug (CONNECTION, " -> success; sending fingerprint...");
391 if (!send_all (fd, fingerprint, strlen (fingerprint), 5 * 1000000))
392 goto out;
393
394 debug (CONNECTION, " -> success; waiting for reply...");
395
396 /* wait for the systemd job status reply */
397 if (!recv_alnum (fd, reply, sizeof reply, 30 * 1000000))
398 goto out;
399
400 debug (CONNECTION, " -> got reply '%s'...", reply);
401 status = strcmp (reply, "done") == 0;
402
403 out:
404 debug (CONNECTION, " -> %s.", status ? "success" : "fail");
405
406 if (fd != -1)
407 close (fd);
408
409 return status;
410 }
411
412 static bool
413 connection_connect_to_dynamic_wsinstance (Connection *self)
414 {
415 char sockname[80];
416 int r;
417
418 assert (self->tls != NULL);
419
420 r = snprintf (sockname, sizeof sockname, "https@%s.sock", self->wsinstance);
421 assert (0 < r && r < sizeof sockname);
422
423 debug (CONNECTION, "Connecting to dynamic https instance %s...", sockname);
424
425 /* fast path: the socket already exists, so we can just connect to it */
426 if (af_unix_connectat (self->ws_fd, parameters.wsinstance_sockdir, sockname) == 0)
427 return true;
428
429 /* EACCES: systemd does not atomically set the socket's permissions before we try to connect to it */
430 if (errno != ENOENT && errno != ECONNREFUSED && errno != EACCES)
431 warn ("connect(%s) failed on the first attempt", sockname);
432
433 debug (CONNECTION, " -> failed (%m). Requesting activation.");
434 /* otherwise, ask for the instance to be started */
435 if (!request_dynamic_wsinstance (self->wsinstance))
436 return false;
437
438 /* ... and try one more time. */
439 debug (CONNECTION, " -> trying again");
440 if (af_unix_connectat (self->ws_fd, parameters.wsinstance_sockdir, sockname) != 0)
441 {
442 warn ("connect(%s) failed on the second attempt", sockname);
443 return false;
444 }
445
446 /* otherwise, we're now connected */
447 debug (CONNECTION, " -> success!");
448 return true;
449 }
450
451 static bool
452 connection_is_to_localhost (Connection *self)
453 {
454 struct sockaddr_storage address;
455 socklen_t address_len = sizeof address;
456
457 /* NB: We check our own socket name, not the peer. That lets us find
458 * out if the connection was made to 127.0.0.1, or some other address.
459 *
460 * In the case that the client connects to 127.0.0.2, for example, the
461 * peer socket is still 127.0.0.1.
462 */
463 if (getsockname (self->client_fd, (struct sockaddr *) &address, &address_len) != 0)
464 return false;
465
466 switch (address.ss_family)
467 {
468 case AF_UNIX:
469 return true;
470
471 case AF_INET:
472 {
473 struct in_addr *addr4 = &((struct sockaddr_in *) &address)->sin_addr;
474 return addr4->s_addr == htonl (INADDR_LOOPBACK);
475 }
476
477 case AF_INET6:
478 {
479 struct in6_addr *addr6 = &((struct sockaddr_in6 *) &address)->sin6_addr;
480
481 /* Need to handle both ::ffff:127.0.0.1 as well as ::1
482 * This is ugly, but there doesn't seem to be a better (static) way... */
483 const struct in6_addr v4_loopback = { { { 0,0,0,0,0,0,0,0,0,0,0xff,0xff,127,0,0,1 } } };
484 return IN6_IS_ADDR_LOOPBACK (addr6) || IN6_ARE_ADDR_EQUAL(addr6, &v4_loopback);
485 }
486
487 default:
488 return false;
489 }
490 }
491
492 static bool
493 connection_connect_to_wsinstance (Connection *self)
494 {
495 if (self->tls == NULL && parameters.require_https && !connection_is_to_localhost (self))
496 {
497 /* server is expecting https connections */
498 self->ws_fd = http_redirect_connect ();
499 if (self->ws_fd == -1)
500 {
501 warn ("failed to connect to httpredirect");
502 return false;
503 }
504
505 return true;
506 }
507
508 self->ws_fd = socket (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
509 if (self->ws_fd == -1)
510 {
511 warn ("failed to create cockpit-ws client socket");
512 return false;
513 }
514
515 if (self->tls == NULL)
516 {
517 /* server is expecting http connections, or localhost is exempt */
518 if (af_unix_connectat (self->ws_fd, parameters.wsinstance_sockdir, "http.sock") != 0)
519 {
520 warn ("connect(http.sock) failed");
521 return false;
522 }
523
524 return true;
525 }
526 else
527 return connection_connect_to_dynamic_wsinstance (self);
528 }
529
530 /**
531 * connection_handshake: Handle first event on client fd
532 *
533 * Check the very first byte of a new connection to tell apart TLS from plain
534 * HTTP. Initialize TLS.
535 */
536 static bool
537 connection_handshake (Connection *self)
538 {
539 char b;
540 int ret;
541
542 assert (self->ws_fd == -1);
543
544 /* Wait for up to 30 seconds to receive the first byte before shutting
545 * down the connection.
546 */
547 struct pollfd pfd = { .fd = self->client_fd, .events = POLLIN };
548 do
549 ret = poll (&pfd, 1, 30000); /* timeout is wrong on syscall restart, but it's fine */
550 while (ret == -1 && errno == EINTR);
551
552 if (ret < 0)
553 err (EXIT_FAILURE, "poll() failed on client connection");
554
555 if (ret == 0)
556 {
557 debug (CONNECTION, "client sent no data in 30 seconds, dropping connection.");
558 return false;
559 }
560
561 /* peek the first byte and see if it's a TLS connection (starting with 22).
562 We can assume that there is some data to read, as this is called in response
563 to an epoll event. */
564 ret = recv (self->client_fd, &b, 1, MSG_PEEK);
565
566 if (ret < 0)
567 {
568 debug (CONNECTION, "could not read first byte: %s", strerror (errno));
569 return false;
570 }
571
572 if (ret == 0) /* EOF */
573 {
574 debug (CONNECTION, "client disconnected without sending any data");
575 return false;
576 }
577
578 if (b == 22)
579 {
580 debug (CONNECTION, "first byte is %i, initializing TLS", (int) b);
581
582 if (parameters.credentials == NULL)
583 {
584 warnx ("got TLS connection, but our server does not have a certificate/key; refusing");
585 return false;
586 }
587
588 ret = gnutls_init (&self->tls, GNUTLS_SERVER | GNUTLS_NO_SIGNAL);
589 if (ret != GNUTLS_E_SUCCESS)
590 {
591 warnx ("gnutls_init failed: %s", gnutls_strerror (ret));
592 return false;
593 }
594
595 ret = gnutls_set_default_priority (self->tls);
596 if (ret != GNUTLS_E_SUCCESS)
597 {
598 warnx ("gnutls_set_default_priority failed: %s", gnutls_strerror (ret));
599 return false;
600 }
601
602 ret = gnutls_credentials_set (self->tls, GNUTLS_CRD_CERTIFICATE,
603 credentials_get (parameters.credentials));
604 if (ret != GNUTLS_E_SUCCESS)
605 {
606 warnx ("gnutls_credentials_set failed: %s", gnutls_strerror (ret));
607 return false;
608 }
609
610 gnutls_session_set_verify_function (self->tls, client_certificate_verify);
611 gnutls_certificate_server_set_request (self->tls, parameters.request_mode);
612 gnutls_handshake_set_timeout (self->tls, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
613 gnutls_transport_set_int (self->tls, self->client_fd);
614
615 debug (CONNECTION, "TLS is initialised; doing handshake");
616
617 do
618 ret = gnutls_handshake (self->tls);
619 while (ret == GNUTLS_E_INTERRUPTED);
620
621 if (ret != GNUTLS_E_SUCCESS)
622 {
623 warnx ("gnutls_handshake failed: %s", gnutls_strerror (ret));
624 return false;
625 }
626
627 debug (CONNECTION, "TLS handshake completed");
628
629 if (!client_certificate_accept (self->tls, parameters.cert_session_dir,
630 &self->wsinstance, &self->client_cert_filename))
631 return false;
632 }
633
634 return true;
635 }
636
637 static void
638 connection_thread_loop (Connection *self)
639 {
640 while (buffer_alive (&self->client_to_ws_buffer) || buffer_alive (&self->ws_to_client_buffer))
641 {
642 short client_events, ws_events;
643 short client_revents, ws_revents;
644 int n_ready;
645
646 client_events = calculate_events (&self->client_to_ws_buffer, &self->ws_to_client_buffer);
647 ws_events = calculate_events (&self->ws_to_client_buffer, &self->client_to_ws_buffer);
648 client_revents = calculate_revents (&self->client_to_ws_buffer, &self->ws_to_client_buffer);
649 ws_revents = calculate_revents (&self->ws_to_client_buffer, &self->client_to_ws_buffer);
650
651 if (self->tls && buffer_can_read (&self->client_to_ws_buffer))
652 client_revents |= POLLIN * (gnutls_record_check_pending (self->tls) != 0);
653
654 debug (POLL, "poll | client %d/x%x/x%x | ws %d/x%x/x%x |",
655 self->client_fd, client_events, client_revents,
656 self->ws_fd, ws_events, ws_revents);
657
658 do
659 {
660 /* don't poll for no events, we'd spin in a POLLHUP loop otherwise */
661 struct pollfd fds[] = { { client_events ? self->client_fd : -1, client_events },
662 { ws_events ? self->ws_fd : -1, ws_events }};
663
664 n_ready = poll (fds, N_ELEMENTS (fds), (client_revents | ws_revents) ? 0 : -1);
665
666 client_revents |= fds[0].revents;
667 ws_revents |= fds[1].revents;
668 }
669 while (n_ready == -1 && errno == EINTR);
670
671 if (n_ready == -1)
672 {
673 if (errno == EINVAL) /* ran out of fds */
674 return;
675 err (EXIT_FAILURE, "poll failed");
676 }
677
678 debug (POLL, "poll result %i | client %d/x%x | ws %d/x%x |", n_ready,
679 self->client_fd, client_revents, self->ws_fd, ws_revents);
680
681 if (self->tls)
682 {
683 if (client_revents & POLLIN)
684 buffer_read_from_tls (&self->client_to_ws_buffer, self->tls);
685
686 if (client_revents & POLLOUT)
687 buffer_write_to_tls (&self->ws_to_client_buffer, self->tls);
688 }
689 else
690 {
691 if (client_revents & POLLIN)
692 buffer_read_from_fd (&self->client_to_ws_buffer, self->client_fd);
693
694 if (client_revents & POLLOUT)
695 buffer_write_to_fd (&self->ws_to_client_buffer, self->client_fd, NULL);
696 }
697
698 if (ws_revents & POLLIN)
699 buffer_read_from_fd (&self->ws_to_client_buffer, self->ws_fd);
700
701 if (ws_revents & POLLOUT)
702 buffer_write_to_fd (&self->client_to_ws_buffer, self->ws_fd, &self->metadata_fd);
703 }
704 }
705
706 static bool
707 connection_create_metadata (Connection *self)
708 {
709 struct sockaddr_storage addr;
710 socklen_t addrsize = sizeof addr;
711 if (getpeername (self->client_fd, (struct sockaddr *) &addr, &addrsize))
712 {
713 debug (CONNECTION, "getpeername(%i) failed: %m. Disconnecting.", self->client_fd);
714 return false;
715 }
716
717 /* maximum we're going to see */
718 char ip[INET6_ADDRSTRLEN + 1 + IF_NAMESIZE + 1];
719 in_port_t port;
720
721 switch (addr.ss_family)
722 {
723 case AF_INET:
724 {
725 struct sockaddr_in *in_addr = (struct sockaddr_in *) &addr;
726
727 port = ntohs (in_addr->sin_port);
728 const char *r = inet_ntop (AF_INET, &in_addr->sin_addr, ip, sizeof ip);
729 assert (r != NULL);
730 }
731 break;
732
733 case AF_INET6:
734 {
735 struct sockaddr_in6 *in6_addr = (struct sockaddr_in6 *) &addr;
736
737 port = ntohs (in6_addr->sin6_port);
738 const char *r = inet_ntop (AF_INET6, &in6_addr->sin6_addr, ip, sizeof ip);
739 assert (r != NULL);
740
741 if (in6_addr->sin6_scope_id)
742 {
743 size_t iplen = strlen (ip);
744
745 ip[iplen++] = '%';
746
747 assert (IF_NAMESIZE < sizeof ip - iplen);
748 if (!if_indextoname (in6_addr->sin6_scope_id, ip + iplen))
749 {
750 /* fallback: just write the index */
751 int r = snprintf (ip + iplen, IF_NAMESIZE, "%u", in6_addr->sin6_scope_id);
752 assert (r < IF_NAMESIZE);
753 }
754
755 /* both snprintf() and if_indextoname() will have added a nul. */
756 }
757 }
758 break;
759
760 case AF_UNIX:
761 /* only used in testing */
762 ip[0] = '\0';
763 port = 0;
764 break;
765
766 default:
767 debug (CONNECTION, "Connection fd %i had unknown peer address family %d. Disconnecting.",
768 self->client_fd, (int) addr.ss_family);
769 return false;
770 }
771
772 debug (CONNECTION, "Connection fd %i is from %s:%d", self->client_fd, ip, port);
773
774 FILE *stream = cockpit_json_print_open_memfd ("cockpit-tls metadata", 1);
775
776 cockpit_json_print_string_property (stream, "origin-ip", ip, -1);
777 cockpit_json_print_integer_property (stream, "origin-port", port);
778
779 if (self->client_cert_filename)
780 cockpit_json_print_string_property (stream, "client-certificate", self->client_cert_filename, -1);
781
782 self->metadata_fd = cockpit_json_print_finish_memfd (&stream);
783
784 return true;
785 }
786
787 void
788 connection_thread_main (int fd)
789 {
790 Connection self = { .client_fd = fd, .ws_fd = -1, .metadata_fd = -1 };
791
792 assert (!buffer_can_write (&self.client_to_ws_buffer));
793 assert (!buffer_can_write (&self.ws_to_client_buffer));
794 assert (!self.tls);
795
796 #ifdef DEBUG
797 self.client_to_ws_buffer.name = "client-to-ws";
798 self.ws_to_client_buffer.name = "ws-to-client";
799 #endif
800
801 debug (CONNECTION, "New thread for fd %i", fd);
802
803 if (connection_handshake (&self) &&
804 connection_create_metadata (&self) &&
805 connection_connect_to_wsinstance (&self))
806 connection_thread_loop (&self);
807
808 debug (CONNECTION, "Thread for fd %i is going to exit now", fd);
809
810 free (self.wsinstance);
811
812 if (self.client_cert_filename)
813 client_certificate_unlink_and_free (parameters.cert_session_dir, self.client_cert_filename);
814
815 if (self.tls)
816 gnutls_deinit (self.tls);
817
818 if (self.client_fd != -1)
819 close (self.client_fd);
820
821 if (self.ws_fd != -1)
822 close (self.ws_fd);
823
824 if (self.metadata_fd != -1)
825 close (self.metadata_fd);
826 }
827
828 /**
829 * connection_crypto_init: Initialise TLS support
830 *
831 * This should be called after server_init() in order to enable TLS
832 * support for connections. If this function is not called, the server
833 * will only be able to handle http requests.
834 *
835 * Loads certificate/key pairs named `{n}.crt` and `{n}.key` for values
836 * of n from 0 until the first missing `.crt` file. Files are deleted
837 * after loading to avoid leaving unnecessary copies of secrets lying
838 * around.
839 *
840 * @cert_dirfd: Directory fd containing certificate/key files
841 * @allow_unencrypted: Whether to allow plain HTTP connections
842 * @request_mode: Whether to ask for client certificates
843 */
844 void
845 connection_crypto_init (int cert_dirfd,
846 bool allow_unencrypted,
847 gnutls_certificate_request_t request_mode)
848 {
849 parameters.credentials = credentials_load (cert_dirfd);
850 if (parameters.credentials == NULL)
851 errx (EXIT_FAILURE, "Failed to load certificates from directory");
852
853 parameters.request_mode = request_mode;
854 /* If we aren't called, then require_https is false */
855 parameters.require_https = !allow_unencrypted;
856 }
857
858 void
859 connection_set_directories (const char *wsinstance_sockdir,
860 const char *runtime_directory)
861 {
862 assert (parameters.wsinstance_sockdir == -1);
863 assert (parameters.cert_session_dir == -1);
864
865 assert (wsinstance_sockdir != NULL);
866 assert (runtime_directory != NULL);
867
868 parameters.wsinstance_sockdir = open (wsinstance_sockdir, O_PATH | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
869 if (parameters.wsinstance_sockdir == -1)
870 err (EXIT_FAILURE, "Unable to open wsinstance sockdir %s", wsinstance_sockdir);
871
872 int runtimedir_fd = open (runtime_directory, O_PATH | O_DIRECTORY | O_NOFOLLOW);
873 if (runtimedir_fd == -1)
874 err (EXIT_FAILURE, "Unable to open runtime directory %s", runtime_directory);
875
876 if (mkdirat (runtimedir_fd, "clients", 0700) != 0)
877 err (EXIT_FAILURE, "mkdir: %s/clients", runtime_directory);
878
879 parameters.cert_session_dir = openat (runtimedir_fd, "clients", O_PATH | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
880 if (parameters.cert_session_dir == -1)
881 err (EXIT_FAILURE, "Unable to open certificate directory %s/clients", runtime_directory);
882
883 close (runtimedir_fd);
884 }
885
886 void
887 connection_cleanup (void)
888 {
889 assert (parameters.wsinstance_sockdir != -1);
890 assert (parameters.cert_session_dir != -1);
891
892 if (parameters.credentials)
893 {
894 credentials_unref (parameters.credentials);
895 parameters.credentials = NULL;
896 }
897
898 parameters.require_https = false;
899
900 close (parameters.cert_session_dir);
901 parameters.cert_session_dir = -1;
902
903 close (parameters.wsinstance_sockdir);
904 parameters.wsinstance_sockdir = -1;
905 }