Debian Codegraph @

src/tls/test-server.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 <arpa/inet.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <signal.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <netinet/in.h>
15 #include <sys/poll.h>
16 #include <sys/socket.h>
17 #include <sys/wait.h>
18
19 #include <glib.h>
20 #include <glib/gstdio.h>
21 #include <gnutls/x509.h>
22
23 #include "connection.h"
24 #include "testing.h"
25 #include "server.h"
26 #include "utils.h"
27 #include "testlib/cockpittest.h"
28
29 #define SOCKET_ACTIVATION_HELPER BUILDDIR "/socket-activation-helper"
30 #define COCKPIT_WS BUILDDIR "/cockpit-ws"
31 /* this has a corresponding mock-server.key */
32 #define CERTFILE SRCDIR "/test/data/mock-server.crt"
33 #define KEYFILE SRCDIR "/test/data/mock-server.key"
34 #define ECC_CERTFILE SRCDIR "/test/data/mock-ecc.crt"
35 #define ECC_KEYFILE SRCDIR "/test/data/mock-ecc.key"
36
37 #define CLIENT_CERTFILE SRCDIR "/src/tls/ca/alice.pem"
38 #define CLIENT_KEYFILE SRCDIR "/src/tls/ca/alice.key"
39 #define ALTERNATE_CERTFILE SRCDIR "/src/tls/ca/bob.pem"
40 #define ALTERNATE_KEYFILE SRCDIR "/src/tls/ca/bob.key"
41 #define CLIENT_EXPIRED_CERTFILE SRCDIR "/src/tls/ca/alice-expired.pem"
42
43 typedef struct {
44 gchar *ws_socket_dir;
45 gchar *runtime_dir;
46 gchar *clients_dir;
47 gchar *cgroup_line;
48 GPid ws_spawner;
49 struct sockaddr_in6 server_addr;
50 } TestCase;
51
52 typedef struct {
53 const char *certfile;
54 const char *keyfile;
55 const char *certfile2;
56 const char *keyfile2;
57 int cert_request_mode;
58 int idle_timeout;
59 const char *client_crt;
60 const char *client_key;
61 const char *client_fingerprint;
62 const char *priority;
63 int expected_pk_algo;
64 unsigned int max_connection_count;
65 } TestFixture;
66
67 static const TestFixture fixture_max_connection_count_10 = {
68 .max_connection_count = 10,
69 };
70
71 static const TestFixture fixture_separate_crt_key = {
72 .certfile = CERTFILE,
73 .keyfile = KEYFILE,
74 };
75
76 static const TestFixture fixture_separate_crt_key_client_cert = {
77 .certfile = CERTFILE,
78 .keyfile = KEYFILE,
79 .cert_request_mode = GNUTLS_CERT_REQUEST,
80 .client_crt = CLIENT_CERTFILE,
81 .client_key = CLIENT_KEYFILE,
82 .client_fingerprint = CLIENT_CERT_FINGERPRINT,
83 };
84
85 static const TestFixture fixture_expired_client_cert = {
86 .certfile = CERTFILE,
87 .keyfile = KEYFILE,
88 .cert_request_mode = GNUTLS_CERT_REQUEST,
89 .client_crt = CLIENT_EXPIRED_CERTFILE,
90 .client_key = CLIENT_KEYFILE,
91 .client_fingerprint = CLIENT_EXPIRED_FINGERPRINT,
92 };
93
94 static const TestFixture fixture_alternate_client_cert = {
95 .certfile = CERTFILE,
96 .keyfile = KEYFILE,
97 .cert_request_mode = GNUTLS_CERT_REQUEST,
98 .client_crt = ALTERNATE_CERTFILE,
99 .client_key = ALTERNATE_KEYFILE,
100 .client_fingerprint = ALTERNATE_FINGERPRINT,
101 };
102
103 static const TestFixture fixture_run_idle = {
104 .idle_timeout = 1,
105 };
106
107 static const TestFixture fixture_multiple_certs_ecdsa = {
108 .certfile = CERTFILE,
109 .keyfile = KEYFILE,
110 .certfile2 = ECC_CERTFILE,
111 .keyfile2 = ECC_KEYFILE,
112 .priority = "NORMAL:-SIGN-ALL:+SIGN-ECDSA-SECP256R1-SHA256",
113 .expected_pk_algo = GNUTLS_PK_ECDSA,
114 };
115
116 static const TestFixture fixture_multiple_certs_rsa = {
117 .certfile = CERTFILE,
118 .keyfile = KEYFILE,
119 .certfile2 = ECC_CERTFILE,
120 .keyfile2 = ECC_KEYFILE,
121 .priority = "NORMAL:-SIGN-ALL:+SIGN-RSA-SHA256:+SIGN-RSA-PSS-RSAE-SHA256",
122 .expected_pk_algo = GNUTLS_PK_RSA,
123 };
124
125 /* for forking test cases, where server's SIGCHLD handling gets in the way */
126 static void
127 block_sigchld (void)
128 {
129 const struct sigaction child_action = { .sa_handler = SIG_DFL };
130 g_assert_cmpint (sigaction (SIGCHLD, &child_action, NULL), ==, 0);
131 }
132
133 /* check if we have a client certificate for a given cgroup */
134 static bool
135 check_for_certfile (TestCase *tc,
136 char **out_contents)
137 {
138 g_autoptr(GDir) dir = g_dir_open (tc->clients_dir, 0, NULL);
139 g_assert (dir != NULL);
140
141 const char *name;
142 while ((name = g_dir_read_name (dir)))
143 {
144 g_autofree char *filename = g_build_filename (tc->clients_dir, name, NULL);
145
146 g_autofree char *contents = NULL;
147 g_autoptr(GError) error = NULL;
148 if (!g_file_get_contents (filename, &contents, NULL, &error))
149 {
150 /* files are flying around all the time: this might reasonably fail */
151 if (g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
152 continue;
153 g_assert_no_error (error);
154 g_assert_not_reached ();
155 }
156
157 if (g_str_has_prefix (contents, tc->cgroup_line))
158 {
159 if (out_contents)
160 *out_contents = g_steal_pointer (&contents);
161
162 return true;
163 }
164 }
165
166 return false;
167 }
168
169 static int
170 do_connect (TestCase *tc)
171 {
172 int fd = socket (AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
173 g_assert_cmpint (fd, >, 0);
174 if (connect (fd, (struct sockaddr *) &tc->server_addr, sizeof (tc->server_addr)) < 0)
175 {
176 close (fd);
177 return -errno;
178 }
179 else
180 {
181 return fd;
182 }
183 }
184
185 /* Explicitly connect using IPv4 to the dual-stack server */
186 static int
187 do_connect_ipv4 (TestCase *tc)
188 {
189 struct sockaddr_in sa;
190 int fd = socket (AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
191 g_assert_cmpint (fd, >, 0);
192
193 memset (&sa, 0, sizeof (sa));
194 sa.sin_family = AF_INET;
195 sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
196 sa.sin_port = tc->server_addr.sin6_port;
197
198 if (connect (fd, (struct sockaddr *) &sa, sizeof (sa)) < 0)
199 {
200 close (fd);
201 return -errno;
202 }
203 else
204 {
205 return fd;
206 }
207 }
208
209 /* Connect using IPv4-mapped IPv6 address (::ffff:x.x.x.x) */
210 static int
211 do_connect_ipv4_mapped (TestCase *tc, const char *ipv4_mapped_addr)
212 {
213 struct sockaddr_in6 sa;
214 int fd = socket (AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0);
215 g_assert_cmpint (fd, >, 0);
216
217 /* Use server_addr but change address to specified IPv4-mapped address */
218 memcpy (&sa, &tc->server_addr, sizeof (sa));
219 g_assert_cmpint (inet_pton (AF_INET6, ipv4_mapped_addr, &sa.sin6_addr), ==, 1);
220
221 if (connect (fd, (struct sockaddr *) &sa, sizeof (sa)) < 0)
222 {
223 close (fd);
224 return -errno;
225 }
226 else
227 {
228 return fd;
229 }
230 }
231
232 static void
233 send_request (int fd, const char *request)
234 {
235 g_assert_cmpint (fd, >, 0);
236 g_assert_cmpint (write (fd, request, strlen (request)), ==, strlen (request));
237 }
238
239 static const char*
240 recv_reply (int fd, char *buf, size_t buflen)
241 {
242 ssize_t len;
243
244 len = recv (fd, buf, buflen - 1, MSG_DONTWAIT);
245 close (fd);
246 if (len < 0)
247 g_error ("recv_reply: unexpected error: %m");
248 g_assert_cmpint (len, >=, 50);
249 buf[len] = '\0'; /* so that we can use string functions on it */
250
251 return buf;
252 }
253
254 static const char*
255 do_request_fd (int fd, const char *request)
256 {
257 static char buf[4096];
258 int res;
259
260 send_request (fd, request);
261 /* wait until data is available */
262 for (int timeout = 0; timeout < 100; ++timeout) {
263 res = recv (fd, buf, 100, MSG_PEEK | MSG_DONTWAIT);
264 if (res >= 50)
265 return recv_reply (fd, buf, sizeof (buf));
266
267 server_poll_event (100);
268 }
269
270 g_error ("timed out waiting for enough data to become available: res=%d, error: %m", res);
271 }
272
273 static const char*
274 do_request (TestCase *tc, const char *request)
275 {
276 int fd = do_connect (tc);
277 return do_request_fd (fd, request);
278 }
279
280 static void
281 assert_http (TestCase *tc)
282 {
283 const char *res = do_request (tc, "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n");
284 /* This succeeds (200 OK) when building in-tree, but fails with dist-check due to missing doc root */
285 if (strstr (res, "200 OK"))
286 {
287 cockpit_assert_strmatch (res, "HTTP/1.1 200 OK\r\n"
288 "Content-Type: text/html\r\n"
289 "Content-Security-Policy: connect-src 'self' http://localhost ws://localhost;*");
290 }
291 else
292 {
293 cockpit_assert_strmatch (res, "HTTP/1.1 404 Not Found\r\nContent-Type: text/html*");
294 }
295 }
296
297 static void
298 assert_https_outcome (TestCase *tc,
299 const TestFixture *fixture,
300 unsigned expected_server_certs,
301 bool expect_tls_failure)
302 {
303 pid_t pid;
304 int status = -1;
305
306 block_sigchld ();
307
308 /* do the connection in a subprocess, as gnutls_handshake is synchronous */
309 pid = fork ();
310 if (pid < 0)
311 g_error ("failed to fork: %m");
312 if (pid == 0)
313 {
314 const char request[] = "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n";
315 char buf[4096];
316 gnutls_session_t session;
317 gnutls_certificate_credentials_t xcred;
318 const gnutls_datum_t *server_certs;
319 unsigned server_certs_len;
320 ssize_t len;
321 int ret;
322 int fd = do_connect (tc);
323
324 g_assert_cmpint (fd, >, 0);
325
326 g_assert_cmpint (gnutls_init (&session, GNUTLS_CLIENT), ==, GNUTLS_E_SUCCESS);
327 gnutls_transport_set_int (session, fd);
328 if (fixture && fixture->priority)
329 g_assert_cmpint (gnutls_priority_set_direct (session, fixture->priority, NULL), ==, GNUTLS_E_SUCCESS);
330 else
331 g_assert_cmpint (gnutls_set_default_priority (session), ==, GNUTLS_E_SUCCESS);
332 gnutls_handshake_set_timeout(session, 5000);
333 g_assert_cmpint (gnutls_certificate_allocate_credentials (&xcred), ==, GNUTLS_E_SUCCESS);
334 g_assert_cmpint (gnutls_certificate_set_x509_system_trust (xcred), >=, 0);
335 if (fixture && fixture->client_crt)
336 {
337 g_assert (fixture->client_key);
338 g_assert_cmpint (gnutls_certificate_set_x509_key_file (xcred,
339 fixture->client_crt,
340 fixture->client_key,
341 GNUTLS_X509_FMT_PEM),
342 ==, GNUTLS_E_SUCCESS);;
343 }
344 g_assert_cmpint (gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred), ==, GNUTLS_E_SUCCESS);
345
346 ret = gnutls_handshake (session);
347 if (ret != GNUTLS_E_SUCCESS)
348 {
349 if (expect_tls_failure)
350 exit (0);
351 else
352 g_error ("Handshake failed: %s", gnutls_strerror (ret));
353 }
354
355 /* check server certificate */
356 server_certs = gnutls_certificate_get_peers (session, &server_certs_len);
357 g_assert (server_certs);
358 g_assert_cmpuint (server_certs_len, ==, expected_server_certs);
359
360 /* check server certificate algorithm if requested */
361 if (fixture && fixture->expected_pk_algo)
362 {
363 gnutls_x509_crt_t cert;
364 g_assert_cmpint (gnutls_x509_crt_init (&cert), ==, GNUTLS_E_SUCCESS);
365 g_assert_cmpint (gnutls_x509_crt_import (cert, &server_certs[0], GNUTLS_X509_FMT_DER),
366 ==, GNUTLS_E_SUCCESS);
367 g_assert_cmpint (gnutls_x509_crt_get_pk_algorithm (cert, NULL), ==, fixture->expected_pk_algo);
368 gnutls_x509_crt_deinit (cert);
369 }
370
371 /* send request, read response */
372 len = gnutls_record_send (session, request, sizeof (request));
373 if (len < 0 && expect_tls_failure)
374 exit (0);
375 g_assert_cmpint (len, ==, sizeof (request));
376
377 len = gnutls_record_recv (session, buf, sizeof (buf) - 1);
378 if (len < 0 && expect_tls_failure)
379 exit (0);
380 g_assert_cmpint (len, >=, 100);
381 g_assert_cmpint (len, <=, sizeof (buf) - 1);
382
383 buf[len] = '\0'; /* so that we can use string functions on it */
384 /* This succeeds (200 OK) when building in-tree, but fails with dist-check due to missing doc root */
385 if (strstr (buf, "200 OK"))
386 {
387 cockpit_assert_strmatch (buf, "HTTP/1.1 200 OK\r\n"
388 "Content-Type: text/html\r\n"
389 "Content-Security-Policy: connect-src 'self' https://localhost wss://localhost;*");
390 }
391 else
392 {
393 cockpit_assert_strmatch (buf, "HTTP/1.1 404 Not Found\r\nContent-Type: text/html*");
394 }
395
396 /* check client certificate in state dir */
397 if (fixture && fixture->client_crt && tc->cgroup_line)
398 {
399 if (fixture->cert_request_mode != GNUTLS_CERT_IGNORE)
400 {
401 g_autofree char *cert_file = NULL;
402 g_autofree char *expected_pem = NULL;
403
404 g_assert (check_for_certfile (tc, &cert_file));
405 g_assert (g_file_get_contents (fixture->client_crt, &expected_pem, NULL, NULL));
406 g_assert (g_str_has_suffix (cert_file, expected_pem));
407 }
408 else
409 {
410 g_assert (!check_for_certfile (tc, NULL));
411 }
412 }
413
414 g_assert_cmpint (gnutls_bye (session, GNUTLS_SHUT_RDWR), ==, GNUTLS_E_SUCCESS);
415
416 g_assert_false (expect_tls_failure);
417
418 close (fd);
419 exit (0);
420 }
421
422 for (int retry = 0; retry < 100 && waitpid (pid, &status, WNOHANG) <= 0; ++retry)
423 server_poll_event (200);
424 g_assert_cmpint (status, ==, 0);
425
426 /* cleans up client certificate after closing connection */
427 g_assert (!check_for_certfile (tc, NULL));
428 }
429
430 static void
431 assert_https (TestCase *tc, const TestFixture *fixture, unsigned expected_server_certs)
432 {
433 assert_https_outcome (tc, fixture, expected_server_certs, false);
434 }
435
436 static void
437 setup (TestCase *tc, gconstpointer data)
438 {
439 const TestFixture *fixture = data;
440 g_autoptr(GError) error = NULL;
441
442 alarm (120);
443
444 tc->ws_socket_dir = g_dir_make_tmp ("server.wssock.XXXXXX", NULL);
445 g_assert (tc->ws_socket_dir);
446
447 /* This absolutely must be on a real filesystem: overlayfs (as often
448 * seen for /tmp in containers) doesn't work. /dev/shm is always
449 * tmpfs, which works nicely (and matches what we expect to be at /run
450 * when we use this code in production).
451 */
452 char runtime_dir_template[] = "/dev/shm/server.runtime.XXXXXX";
453 tc->runtime_dir = g_mkdtemp (runtime_dir_template);
454 g_assert (tc->runtime_dir);
455 tc->runtime_dir = g_strdup (tc->runtime_dir);
456 tc->clients_dir = g_build_filename (tc->runtime_dir, "clients", NULL);
457
458 if (fixture && fixture->client_fingerprint)
459 tc->cgroup_line = g_strdup_printf ("0::/system.slice/system-cockpithttps.slice/cockpit-wsinstance-https@%s.service\n", fixture->client_fingerprint);
460
461 gchar* sah_argv[] = { SOCKET_ACTIVATION_HELPER, COCKPIT_WS, tc->ws_socket_dir, NULL };
462 if (!g_spawn_async (NULL, sah_argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &tc->ws_spawner, &error))
463 g_error ("Failed to spawn " SOCKET_ACTIVATION_HELPER ": %s", error->message);
464
465 /* wait until socket activation helper is ready */
466 int socket_dir_fd = open (tc->ws_socket_dir, O_RDONLY | O_DIRECTORY);
467 g_assert_cmpint (socket_dir_fd, >=, 0);
468 for (int retry = 0; retry < 200; ++retry)
469 {
470 if (faccessat (socket_dir_fd, "ready", F_OK, 0) == 0)
471 break;
472 g_usleep (10000);
473 }
474 close (socket_dir_fd);
475
476 unsigned max_connection_count = (fixture && fixture->max_connection_count != 0) ? fixture->max_connection_count : 500;
477
478 /* Let the kernel assign a port */
479 server_init (tc->ws_socket_dir, tc->runtime_dir, fixture ? fixture->idle_timeout : 0, 0, max_connection_count);
480
481 if (fixture && fixture->certfile)
482 {
483 /* Set up certs directory with 0.crt and 0.key */
484 g_autofree gchar *certs_dir = g_build_filename (tc->runtime_dir, "tls/server", NULL);
485 g_assert_cmpint (g_mkdir_with_parents (certs_dir, 0700), ==, 0);
486
487 const char *sources[] = { fixture->certfile, fixture->keyfile,
488 fixture->certfile2, fixture->keyfile2 };
489 const char *dests[] = { "0.crt", "0.key", "1.crt", "1.key" };
490 for (int i = 0; i < G_N_ELEMENTS (sources) && sources[i]; i++)
491 {
492 g_autofree gchar *contents = NULL;
493 g_autofree gchar *dest = g_build_filename (certs_dir, dests[i], NULL);
494 g_assert (g_file_get_contents (sources[i], &contents, NULL, NULL));
495 g_assert (g_file_set_contents (dest, contents, -1, NULL));
496 }
497
498 int cert_dirfd = open (certs_dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
499 g_assert_cmpint (cert_dirfd, >=, 0);
500 connection_crypto_init (cert_dirfd, false, fixture->cert_request_mode);
501 close (cert_dirfd);
502 }
503
504 /* Figure out the socket address we ought to connect to */
505 socklen_t addrlen = sizeof tc->server_addr;
506 int r = getsockname (server_get_listener (), (struct sockaddr *) &tc->server_addr, &addrlen);
507 g_assert_no_errno (r);
508
509 /* Sanity check */
510 g_assert_cmpint (addrlen, ==, sizeof tc->server_addr);
511 g_assert_cmpint (tc->server_addr.sin6_family, ==, AF_INET6);
512 }
513
514 static void
515 teardown (TestCase *tc, gconstpointer data)
516 {
517 for (int i = 0; i < 100 && server_num_connections (); i++) /* 10s */
518 g_usleep (100000); /* 0.1s */
519
520 server_cleanup ();
521 g_assert_cmpint (kill (tc->ws_spawner, SIGTERM), ==, 0);
522 g_assert_cmpint (waitpid (tc->ws_spawner, NULL, 0), ==, tc->ws_spawner);
523
524 /* all children got cleaned up */
525 g_assert_cmpint (wait (NULL), ==, -1);
526 g_assert_cmpint (errno, ==, ECHILD);
527 /* connection should fail */
528 /* coverity[leaked_handle : FALSE] */
529 g_assert_cmpint (do_connect (tc), ==, -ECONNREFUSED);
530 g_unsetenv ("COCKPIT_WS_PROCESS_IDLE");
531
532 int socket_dir_fd = open (tc->ws_socket_dir, O_RDONLY | O_DIRECTORY);
533 g_assert_cmpint (socket_dir_fd, >=, 0);
534 g_assert_cmpint (unlinkat (socket_dir_fd, "http.sock", 0), ==, 0);
535 g_assert_cmpint (unlinkat (socket_dir_fd, "https-factory.sock", 0), ==, 0);
536 g_assert_cmpint (unlinkat (socket_dir_fd, "https@" SHA256_NIL ".sock", 0), ==, 0);
537 g_assert_cmpint (unlinkat (socket_dir_fd, "https@" CLIENT_CERT_FINGERPRINT ".sock", 0), ==, 0);
538 g_assert_cmpint (unlinkat (socket_dir_fd, "https@" CLIENT_EXPIRED_FINGERPRINT ".sock", 0), ==, 0);
539 g_assert_cmpint (unlinkat (socket_dir_fd, "https@" ALTERNATE_FINGERPRINT ".sock", 0), ==, 0);
540 g_assert_cmpint (unlinkat (socket_dir_fd, "ready", 0), ==, 0);
541 close (socket_dir_fd);
542 g_assert_cmpint (g_rmdir (tc->ws_socket_dir), ==, 0);
543 g_free (tc->ws_socket_dir);
544
545 g_free (tc->cgroup_line);
546
547 g_assert_cmpint (g_rmdir (tc->clients_dir), ==, 0);
548 g_free (tc->clients_dir);
549
550 /* We use only rmdir() to verity that certificate_load() definitely
551 * deleted all of the key material. We want to make sure we don't see
552 * `ENOTEMPTY`.
553 */
554 g_autofree gchar *tls_dir = g_build_filename (tc->runtime_dir, "tls", NULL);
555 g_autofree gchar *certs_dir = g_build_filename (tls_dir, "server", NULL);
556 if (g_rmdir (certs_dir) != 0 && errno != ENOENT)
557 g_error ("rmdir %s: %s", certs_dir, g_strerror (errno));
558 if (g_rmdir (tls_dir) != 0 && errno != ENOENT)
559 g_error ("rmdir %s: %s", tls_dir, g_strerror (errno));
560 g_assert_cmpint (g_rmdir (tc->runtime_dir), ==, 0);
561 g_free (tc->runtime_dir);
562
563 alarm (0);
564 }
565
566 static void
567 test_no_tls_single (TestCase *tc, gconstpointer data)
568 {
569 g_assert_cmpuint (server_num_connections (), ==, 0);
570 assert_http (tc);
571
572 /* let the server process "peer has closed connection" */
573 for (int retries = 0; retries < 10 && server_num_connections () == 1; ++retries)
574 server_poll_event (100);
575 g_assert_cmpuint (server_num_connections (), ==, 0);
576 }
577
578 static void
579 test_no_tls_many_serial (TestCase *tc, gconstpointer data)
580 {
581 for (int i = 0; i < 20; ++i)
582 assert_http (tc);
583 }
584
585 static void
586 test_tls_blocked_handshake (TestCase *tc, gconstpointer data)
587 {
588 block_sigchld ();
589
590 pid_t pid = fork ();
591 if (pid == -1)
592 g_error ("fork failed: %m");
593
594 if (pid == 0)
595 {
596 /* child */
597 gint first_fd = do_connect (tc);
598 send_request (first_fd, "\x16"); /* start the TLS handshake */
599
600 /* Make sure the byte gets there before the next connection request */
601 sleep (1);
602
603 /* make sure we can do a second connection while the first one is
604 * blocked in the handshake
605 */
606 gint second_fd = do_connect (tc);
607 send_request (second_fd, "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n");
608
609 /* wait 10 seconds for the reply */
610 struct pollfd pfd = { .fd = second_fd, .events = POLLIN };
611 g_assert_cmpint (poll (&pfd, 1, 10000), ==, 1);
612 close (second_fd);
613
614 close (first_fd);
615 exit (0);
616 }
617 else
618 {
619 /* parent */
620 int status;
621
622 while (waitpid (pid, &status, WNOHANG) <= 0)
623 server_poll_event (50);
624 g_assert_cmpint (status, ==, 0);
625 }
626 }
627
628 static void
629 test_no_tls_many_parallel (TestCase *tc, gconstpointer data)
630 {
631 int i;
632
633 block_sigchld ();
634
635 for (i = 0; i < 20; ++i)
636 {
637 pid_t pid = fork ();
638 if (pid < 0)
639 g_error ("failed to fork: %m");
640
641 if (pid > 0)
642 continue;
643
644 /* child */
645 char buf[4096];
646 int fd = do_connect (tc);
647
648 server_cleanup ();
649
650 send_request (fd, "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n");
651 /* wait until data is available */
652 for (int timeout = 0; timeout < 10 && recv (fd, buf, 100, MSG_PEEK | MSG_DONTWAIT) < 100; ++timeout)
653 sleep (1);
654 recv_reply (fd, buf, sizeof (buf));
655 /* This succeeds (200 OK) when building in-tree, but fails with dist-check due to missing doc root */
656 if (strstr (buf, "200 OK"))
657 cockpit_assert_strmatch (buf, "HTTP/1.1 200 OK*");
658 else
659 cockpit_assert_strmatch (buf, "HTTP/1.1 404 Not Found*");
660 exit (0);
661 }
662
663 /* wait until all i child processes have finished */
664 while (i > 0)
665 {
666 int status;
667 int r = waitpid (-1, &status, WNOHANG);
668 g_assert_cmpint (r, >=, 0);
669 if (r == 0)
670 {
671 server_poll_event (50);
672 }
673 else
674 {
675 g_assert_cmpint (status, ==, 0);
676 --i;
677 }
678 }
679 }
680
681 static void
682 test_no_tls_too_many_parallel (TestCase *tc, gconstpointer data)
683 {
684 int i;
685 int fds[20];
686
687 const char *request = "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n";
688
689 for (i = 0; i < 20; ++i)
690 {
691 fds[i] = do_connect (tc);
692 g_assert_cmpint (fds[i], >, 0);
693 server_poll_event (50);
694 }
695
696 for (i = 0; i < 20; ++i)
697 {
698 if (i < 10)
699 {
700 /* the first 10 are allowed to connect and will receive a reply */
701 do_request_fd (fds[i], request);
702 }
703 else
704 {
705 /* the rest gets disconnected immediately */
706 int r = write (fds[i], request, strlen (request));
707 g_assert (r == -1 && errno == ECONNRESET);
708 }
709
710 close(fds[i]);
711 }
712 }
713
714 static void
715 test_no_tls_redirect (TestCase *tc, gconstpointer data)
716 {
717 struct sockaddr *sa = (struct sockaddr *) &tc->server_addr;
718
719 /* Server uses IPv6 dual-stack socket */
720 g_assert_cmpint (sa->sa_family, ==, AF_INET6);
721
722 /* Connect to non-localhost address (127.0.0.2 as IPv4-mapped IPv6) to test redirect logic */
723 int fd = do_connect_ipv4_mapped (tc, "::ffff:127.0.0.2");
724 g_assert_cmpint (fd, >, 0);
725
726 /* without TLS support it should not redirect */
727 const char *res = do_request_fd (fd, "GET / HTTP/1.0\r\nHost: some.remote:1234\r\n\r\n");
728 /* This succeeds (200 OK) when building in-tree, but fails with dist-check due to missing doc root */
729 if (strstr (res, "200 OK"))
730 cockpit_assert_strmatch (res, "HTTP/1.1 200 OK*");
731 else
732 cockpit_assert_strmatch (res, "HTTP/1.1 404 Not Found*");
733 }
734
735 static void
736 test_tls_no_client_cert (TestCase *tc, gconstpointer data)
737 {
738 assert_https (tc, data, 1);
739 }
740
741 static void
742 test_tls_no_server_cert (TestCase *tc, gconstpointer data)
743 {
744 assert_http (tc);
745 assert_https_outcome (tc, data, 0, true);
746 assert_http (tc);
747 }
748
749 static void
750 test_tls_redirect (TestCase *tc, gconstpointer data)
751 {
752 struct sockaddr *sa = (struct sockaddr *) &tc->server_addr;
753
754 /* Server uses IPv6 dual-stack socket */
755 g_assert_cmpint (sa->sa_family, ==, AF_INET6);
756
757 /* Connect to non-localhost address (127.0.0.2 as IPv4-mapped IPv6) to test redirect logic */
758 int fd = do_connect_ipv4_mapped (tc, "::ffff:127.0.0.2");
759 g_assert_cmpint (fd, >, 0);
760
761 /* with TLS support it should redirect */
762 const char *res = do_request_fd (fd, "GET / HTTP/1.0\r\nHost: some.remote:1234\r\n\r\n");
763 cockpit_assert_strmatch (res, "HTTP/1.1 301 Moved Permanently*");
764 }
765
766 static void
767 test_tls_redirect_header_safety (TestCase *tc, gconstpointer data)
768 {
769 /* verify that the redirect response doesn't contain any headers from the request,
770 * possibly through crafted host/path values. */
771 int fd = do_connect_ipv4_mapped (tc, "::ffff:127.0.0.2");
772 g_assert_cmpint (fd, >, 0);
773
774 const char *res = do_request_fd (fd, "GET /test HTTP/1.0\r\nHost: some.remote:1234\r\nX-Injected: evil\r\n\r\n");
775
776 cockpit_assert_strmatch (res, "HTTP/1.1 301 Moved Permanently*");
777 cockpit_assert_strmatch (res, "*Location: https://some.remote:1234/test*");
778 g_assert_null (strstr (res, "X-Injected"));
779 g_assert_null (strstr (res, "evil"));
780
781 /* Request headers should not leak into response */
782 fd = do_connect_ipv4_mapped (tc, "::ffff:127.0.0.2");
783 g_assert_cmpint (fd, >, 0);
784
785 res = do_request_fd (fd, "GET /path?query HTTP/1.0\r\nHost: example.org\r\nCookie: secret=data\r\n\r\n");
786 cockpit_assert_strmatch (res, "HTTP/1.1 301 Moved Permanently*");
787 cockpit_assert_strmatch (res, "*Location: https://example.org/path?query*");
788 g_assert_null (strstr (res, "Cookie"));
789 g_assert_null (strstr (res, "secret"));
790
791 /* Verify URL-encoded CRLF in path is safely handled (preserved as literal %0D%0A) */
792 fd = do_connect_ipv4_mapped (tc, "::ffff:127.0.0.2");
793 g_assert_cmpint (fd, >, 0);
794 res = do_request_fd (fd, "GET /path%0D%0A HTTP/1.0\r\nHost: example.org\r\n\r\n");
795 cockpit_assert_strmatch (res, "HTTP/1.1 301 Moved Permanently*");
796 cockpit_assert_strmatch (res, "*Location: https://example.org/path%0D%0A*");
797 /* The URL encoding should not be decoded into actual CRLF */
798 g_assert_null (strstr (res, "path\r\n"));
799 g_assert_null (strstr (res, "path\n"));
800 }
801
802 static void
803 test_tls_client_cert (TestCase *tc, gconstpointer data)
804 {
805 assert_https (tc, data, 1);
806 /* no-cert case is handled by separate ws; pass NULL fixture to not use a client cert */
807 assert_https (tc, NULL, 1);
808 assert_https (tc, data, 1);
809 }
810
811 static void
812 test_tls_client_cert_disabled (TestCase *tc, gconstpointer data)
813 {
814 assert_https (tc, data, 1);
815 /* no-cert case is handled by same ws, as client certs are disabled server-side;
816 pass NULL fixture to not use a client cert */
817 assert_https (tc, NULL, 1);
818 }
819
820 static void
821 test_tls_client_cert_expired (TestCase *tc, gconstpointer data)
822 {
823 /* expect_tls_failure==true only does a coarse-grained check that the request
824 * fails anywhere during handshake or the first send/recv. GnuTLS 3.6.4
825 * introduces TLS 1.3 by default, which has only a two-step handshake: that
826 * does not pick up the server's late failing handshake from the verify
827 * function, only the next read/write attempt does */
828 assert_https_outcome (tc, data, 1, true);
829 }
830
831 static void
832 test_tls_client_cert_parallel (TestCase *tc, gconstpointer data)
833 {
834 const TestFixture *fixture = data;
835 gboolean alternate = strcmp (fixture->client_fingerprint, ALTERNATE_FINGERPRINT) == 0;
836 pid_t pid;
837 int status;
838
839 /* HACK: This testcase runs slowly under valgrind and sometimes fails
840 * inexplicably. It's not likely that we're going to find leaks in
841 * the code with this test, so running it under valgrind is just
842 * costing us pain. Disable it for now.
843 */
844 if (cockpit_test_skip_slow ())
845 return;
846
847 block_sigchld ();
848
849 /* do the connection in a subprocess, as gnutls_handshake is synchronous */
850 pid = fork ();
851 if (pid < 0)
852 g_error ("failed to fork: %m");
853 if (pid == 0)
854 {
855 gnutls_certificate_credentials_t xcred;
856 const unsigned n_connections = 20;
857 int fds[n_connections];
858 gnutls_session_t sessions[n_connections];
859
860 g_assert_cmpint (gnutls_certificate_allocate_credentials (&xcred), ==, GNUTLS_E_SUCCESS);
861 g_assert_cmpint (gnutls_certificate_set_x509_system_trust (xcred), >=, 0);
862 g_assert_cmpint (gnutls_certificate_set_x509_key_file (xcred,
863 fixture->client_crt,
864 fixture->client_key,
865 GNUTLS_X509_FMT_PEM),
866 ==, GNUTLS_E_SUCCESS);
867
868 g_assert (!check_for_certfile (tc, NULL));
869
870 /* start parallel connections; we don't actually need to send/receive anything (i. e. talk to cockpit-ws) --
871 * certificate export and refcounting is entirely done on the client → cockpit-tls side */
872 for (unsigned i = 0; i < n_connections; ++i)
873 {
874 fds[i] = do_connect (tc);
875 g_assert_cmpint (fds[i], >, 0);
876
877 g_assert_cmpint (gnutls_init (&sessions[i], GNUTLS_CLIENT), ==, GNUTLS_E_SUCCESS);
878 gnutls_transport_set_int (sessions[i], fds[i]);
879 g_assert_cmpint (gnutls_set_default_priority (sessions[i]), ==, GNUTLS_E_SUCCESS);
880 g_assert_cmpint (gnutls_credentials_set (sessions[i], GNUTLS_CRD_CERTIFICATE, xcred), ==, GNUTLS_E_SUCCESS);
881 gnutls_handshake_set_timeout(sessions[i], 5000);
882 g_assert_cmpint (gnutls_handshake (sessions[i]), ==, GNUTLS_E_SUCCESS);
883
884 /* the file should be written on first connection, and just exist for the next ones.
885 *
886 * In the "alternate" mode we will receive a "hello" message to tell us that the
887 * server is active (by which time the file will have been created). For the
888 * other case, we have to wait for it to appear.
889 * */
890 if (alternate)
891 {
892 char buffer[6];
893 ssize_t s;
894
895 do
896 s = gnutls_record_recv (sessions[i], buffer, sizeof buffer);
897 while (s == GNUTLS_E_INTERRUPTED);
898 g_assert_cmpint (s, ==, 5);
899 g_assert (memcmp (buffer, "hello", 5) == 0);
900 }
901 else
902 {
903 if (i == 0)
904 {
905 for (int retry = 0; retry < 100; ++retry)
906 {
907 if (check_for_certfile (tc, NULL))
908 break;
909 g_usleep (10000);
910 }
911 }
912 }
913
914 g_assert (check_for_certfile (tc, NULL));
915 }
916
917 /* close the connections again, all but the last one */
918 for (unsigned i = 0; i < n_connections - 1; ++i)
919 {
920 g_assert_cmpint (gnutls_bye (sessions[i], GNUTLS_SHUT_RDWR), ==, GNUTLS_E_SUCCESS);
921 close (fds[i]);
922 }
923
924 if (!alternate)
925 {
926 /* The certificate file should still exist for the last connection, but it might
927 * not *yet* exist (if the last connection failed to initialise before all the
928 * other connections exited, which is a race that we've seen in practice). Wait
929 * for it, as above.
930 */
931 for (int retry = 0;; ++retry)
932 {
933 g_assert_cmpint (retry, <, 100);
934
935 if (check_for_certfile (tc, NULL))
936 break;
937 g_usleep (10000);
938 }
939 }
940 else
941 {
942 /* In the "alternate" case there should be no such strange
943 * races.
944 */
945 g_assert (check_for_certfile (tc, NULL));
946 }
947
948 /* closing last connection removes it */
949 g_assert_cmpint (gnutls_bye (sessions[n_connections - 1], GNUTLS_SHUT_RDWR), ==, GNUTLS_E_SUCCESS);
950 close (fds[n_connections - 1]);
951 for (int retry = 0; retry < 100; ++retry)
952 {
953 if (!check_for_certfile (tc, NULL))
954 break;
955 g_usleep (10000);
956 }
957 g_assert (!check_for_certfile (tc, NULL));
958 exit (0);
959 }
960
961 for (int retry = 0; retry < 200 && waitpid (pid, &status, WNOHANG) <= 0; ++retry)
962 server_poll_event (100);
963 g_assert_cmpint (status, ==, 0);
964 }
965
966 static void
967 test_mixed_protocols (TestCase *tc, gconstpointer data)
968 {
969 assert_https (tc, data, 1);
970 assert_http (tc);
971 assert_https (tc, data, 1);
972 assert_http (tc);
973 }
974
975 static void
976 test_run_idle (TestCase *tc, gconstpointer data)
977 {
978 /* exits after idle without any connections */
979 server_run ();
980
981 /* exits after idle after processing an event */
982 assert_http (tc);
983 server_run ();
984 }
985
986 static void
987 test_ipv4_connection (TestCase *tc, gconstpointer data)
988 {
989 /* Explicitly connect using IPv4 to the dual-stack server */
990 int fd = do_connect_ipv4 (tc);
991 g_assert_cmpint (fd, >, 0);
992
993 const char *reply = do_request_fd (fd, "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n");
994
995 /* This succeeds (200 OK) when building in-tree, but fails with dist-check due to missing doc root */
996 if (strstr (reply, "200 OK"))
997 cockpit_assert_strmatch (reply, "HTTP/1.1 200 OK*");
998 else
999 cockpit_assert_strmatch (reply, "HTTP/1.1 404 Not Found*");
1000 }
1001
1002 int
1003 main (int argc, char *argv[])
1004 {
1005 cockpit_test_init (&argc, &argv);
1006
1007 g_test_add ("/server/no-tls/single-request", TestCase, NULL,
1008 setup, test_no_tls_single, teardown);
1009 g_test_add ("/server/no-tls/many-serial", TestCase, NULL,
1010 setup, test_no_tls_many_serial, teardown);
1011 g_test_add ("/server/no-tls/many-parallel", TestCase, NULL,
1012 setup, test_no_tls_many_parallel, teardown);
1013 g_test_add ("/server/no-tls/too-many-parallel", TestCase, &fixture_max_connection_count_10,
1014 setup, test_no_tls_too_many_parallel, teardown);
1015 g_test_add ("/server/no-tls/redirect", TestCase, NULL,
1016 setup, test_no_tls_redirect, teardown);
1017 g_test_add ("/server/tls/no-client-cert", TestCase, &fixture_separate_crt_key,
1018 setup, test_tls_no_client_cert, teardown);
1019 g_test_add ("/server/tls/client-cert", TestCase, &fixture_separate_crt_key_client_cert,
1020 setup, test_tls_client_cert, teardown);
1021 g_test_add ("/server/tls/client-cert-disabled", TestCase, &fixture_separate_crt_key,
1022 setup, test_tls_client_cert_disabled, teardown);
1023 g_test_add ("/server/tls/client-cert-expired", TestCase, &fixture_expired_client_cert,
1024 setup, test_tls_client_cert_expired, teardown);
1025 g_test_add ("/server/tls/client-cert-parallel", TestCase, &fixture_separate_crt_key_client_cert,
1026 setup, test_tls_client_cert_parallel, teardown);
1027 g_test_add ("/server/tls/client-cert-parallel/alternate", TestCase, &fixture_alternate_client_cert,
1028 setup, test_tls_client_cert_parallel, teardown);
1029 g_test_add ("/server/tls/no-server-cert", TestCase, NULL,
1030 setup, test_tls_no_server_cert, teardown);
1031 g_test_add ("/server/tls/redirect", TestCase, &fixture_separate_crt_key,
1032 setup, test_tls_redirect, teardown);
1033 g_test_add ("/server/tls/redirect-header-safety", TestCase, &fixture_separate_crt_key,
1034 setup, test_tls_redirect_header_safety, teardown);
1035 g_test_add ("/server/tls/blocked-handshake", TestCase, &fixture_separate_crt_key,
1036 setup, test_tls_blocked_handshake, teardown);
1037 g_test_add ("/server/mixed-protocols", TestCase, &fixture_separate_crt_key,
1038 setup, test_mixed_protocols, teardown);
1039 g_test_add ("/server/tls/multiple-certs/ecdsa", TestCase, &fixture_multiple_certs_ecdsa,
1040 setup, test_tls_no_client_cert, teardown);
1041 g_test_add ("/server/tls/multiple-certs/rsa", TestCase, &fixture_multiple_certs_rsa,
1042 setup, test_tls_no_client_cert, teardown);
1043 g_test_add ("/server/run-idle", TestCase, &fixture_run_idle,
1044 setup, test_run_idle, teardown);
1045 g_test_add ("/server/ipv4/connection", TestCase, NULL,
1046 setup, test_ipv4_connection, teardown);
1047
1048 return g_test_run ();
1049 }