1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <sys/eventfd.h>
5 #include <unistd.h>
6
7 #include "alloc-util.h"
8 #include "data-fd-util.h"
9 #include "fd-util.h"
10 #include "fileio.h"
11 #include "macro.h"
12 #include "memory-util.h"
13 #include "missing_syscall.h"
14 #include "mount-util.h"
15 #include "path-util.h"
16 #include "process-util.h"
17 #include "random-util.h"
18 #include "rlimit-util.h"
19 #include "seccomp-util.h"
20 #include "serialize.h"
21 #include "string-util.h"
22 #include "tests.h"
23 #include "tmpfile-util.h"
24
TEST(close_many)25 TEST(close_many) {
26 int fds[3];
27 char name0[] = "/tmp/test-close-many.XXXXXX";
28 char name1[] = "/tmp/test-close-many.XXXXXX";
29 char name2[] = "/tmp/test-close-many.XXXXXX";
30
31 fds[0] = mkostemp_safe(name0);
32 fds[1] = mkostemp_safe(name1);
33 fds[2] = mkostemp_safe(name2);
34
35 close_many(fds, 2);
36
37 assert_se(fcntl(fds[0], F_GETFD) == -1);
38 assert_se(fcntl(fds[1], F_GETFD) == -1);
39 assert_se(fcntl(fds[2], F_GETFD) >= 0);
40
41 safe_close(fds[2]);
42
43 unlink(name0);
44 unlink(name1);
45 unlink(name2);
46 }
47
TEST(close_nointr)48 TEST(close_nointr) {
49 char name[] = "/tmp/test-test-close_nointr.XXXXXX";
50 int fd;
51
52 fd = mkostemp_safe(name);
53 assert_se(fd >= 0);
54 assert_se(close_nointr(fd) >= 0);
55 assert_se(close_nointr(fd) < 0);
56
57 unlink(name);
58 }
59
TEST(same_fd)60 TEST(same_fd) {
61 _cleanup_close_pair_ int p[2] = { -1, -1 };
62 _cleanup_close_ int a = -1, b = -1, c = -1;
63
64 assert_se(pipe2(p, O_CLOEXEC) >= 0);
65 assert_se((a = fcntl(p[0], F_DUPFD, 3)) >= 0);
66 assert_se((b = open("/dev/null", O_RDONLY|O_CLOEXEC)) >= 0);
67 assert_se((c = fcntl(a, F_DUPFD, 3)) >= 0);
68
69 assert_se(same_fd(p[0], p[0]) > 0);
70 assert_se(same_fd(p[1], p[1]) > 0);
71 assert_se(same_fd(a, a) > 0);
72 assert_se(same_fd(b, b) > 0);
73
74 assert_se(same_fd(a, p[0]) > 0);
75 assert_se(same_fd(p[0], a) > 0);
76 assert_se(same_fd(c, p[0]) > 0);
77 assert_se(same_fd(p[0], c) > 0);
78 assert_se(same_fd(a, c) > 0);
79 assert_se(same_fd(c, a) > 0);
80
81 assert_se(same_fd(p[0], p[1]) == 0);
82 assert_se(same_fd(p[1], p[0]) == 0);
83 assert_se(same_fd(p[0], b) == 0);
84 assert_se(same_fd(b, p[0]) == 0);
85 assert_se(same_fd(p[1], a) == 0);
86 assert_se(same_fd(a, p[1]) == 0);
87 assert_se(same_fd(p[1], b) == 0);
88 assert_se(same_fd(b, p[1]) == 0);
89
90 assert_se(same_fd(a, b) == 0);
91 assert_se(same_fd(b, a) == 0);
92 }
93
TEST(open_serialization_fd)94 TEST(open_serialization_fd) {
95 _cleanup_close_ int fd = -1;
96
97 fd = open_serialization_fd("test");
98 assert_se(fd >= 0);
99
100 assert_se(write(fd, "test\n", 5) == 5);
101 }
102
TEST(fd_move_above_stdio)103 TEST(fd_move_above_stdio) {
104 int original_stdin, new_fd;
105
106 original_stdin = fcntl(0, F_DUPFD, 3);
107 assert_se(original_stdin >= 3);
108 assert_se(close_nointr(0) != EBADF);
109
110 new_fd = open("/dev/null", O_RDONLY);
111 assert_se(new_fd == 0);
112
113 new_fd = fd_move_above_stdio(new_fd);
114 assert_se(new_fd >= 3);
115
116 assert_se(dup(original_stdin) == 0);
117 assert_se(close_nointr(original_stdin) != EBADF);
118 assert_se(close_nointr(new_fd) != EBADF);
119 }
120
TEST(rearrange_stdio)121 TEST(rearrange_stdio) {
122 pid_t pid;
123 int r;
124
125 r = safe_fork("rearrange", FORK_WAIT|FORK_LOG, &pid);
126 assert_se(r >= 0);
127
128 if (r == 0) {
129 _cleanup_free_ char *path = NULL;
130 char buffer[10];
131
132 /* Child */
133
134 safe_close(STDERR_FILENO); /* Let's close an fd < 2, to make it more interesting */
135
136 assert_se(rearrange_stdio(-1, -1, -1) >= 0);
137
138 assert_se(fd_get_path(STDIN_FILENO, &path) >= 0);
139 assert_se(path_equal(path, "/dev/null"));
140 path = mfree(path);
141
142 assert_se(fd_get_path(STDOUT_FILENO, &path) >= 0);
143 assert_se(path_equal(path, "/dev/null"));
144 path = mfree(path);
145
146 assert_se(fd_get_path(STDOUT_FILENO, &path) >= 0);
147 assert_se(path_equal(path, "/dev/null"));
148 path = mfree(path);
149
150 safe_close(STDIN_FILENO);
151 safe_close(STDOUT_FILENO);
152 safe_close(STDERR_FILENO);
153
154 {
155 int pair[2];
156 assert_se(pipe(pair) >= 0);
157 assert_se(pair[0] == 0);
158 assert_se(pair[1] == 1);
159 assert_se(fd_move_above_stdio(0) == 3);
160 }
161 assert_se(open("/dev/full", O_WRONLY|O_CLOEXEC) == 0);
162 assert_se(acquire_data_fd("foobar", 6, 0) == 2);
163
164 assert_se(rearrange_stdio(2, 0, 1) >= 0);
165
166 assert_se(write(1, "x", 1) < 0 && errno == ENOSPC);
167 assert_se(write(2, "z", 1) == 1);
168 assert_se(read(3, buffer, sizeof(buffer)) == 1);
169 assert_se(buffer[0] == 'z');
170 assert_se(read(0, buffer, sizeof(buffer)) == 6);
171 assert_se(memcmp(buffer, "foobar", 6) == 0);
172
173 assert_se(rearrange_stdio(-1, 1, 2) >= 0);
174 assert_se(write(1, "a", 1) < 0 && errno == ENOSPC);
175 assert_se(write(2, "y", 1) == 1);
176 assert_se(read(3, buffer, sizeof(buffer)) == 1);
177 assert_se(buffer[0] == 'y');
178
179 assert_se(fd_get_path(0, &path) >= 0);
180 assert_se(path_equal(path, "/dev/null"));
181 path = mfree(path);
182
183 _exit(EXIT_SUCCESS);
184 }
185 }
186
TEST(read_nr_open)187 TEST(read_nr_open) {
188 log_info("nr-open: %i", read_nr_open());
189 }
190
validate_fds(bool opened,const int * fds,size_t n_fds)191 static size_t validate_fds(
192 bool opened,
193 const int *fds,
194 size_t n_fds) {
195
196 size_t c = 0;
197
198 /* Validates that fds in the specified array are one of the following three:
199 *
200 * 1. < 0 (test is skipped) or
201 * 2. opened (if 'opened' param is true) or
202 * 3. closed (if 'opened' param is false)
203 */
204
205 for (size_t i = 0; i < n_fds; i++) {
206 if (fds[i] < 0)
207 continue;
208
209 if (opened)
210 assert_se(fcntl(fds[i], F_GETFD) >= 0);
211 else
212 assert_se(fcntl(fds[i], F_GETFD) < 0 && errno == EBADF);
213
214 c++;
215 }
216
217 return c; /* Return number of fds >= 0 in the array */
218 }
219
test_close_all_fds_inner(void)220 static void test_close_all_fds_inner(void) {
221 _cleanup_free_ int *fds = NULL, *keep = NULL;
222 size_t n_fds, n_keep;
223 int max_fd;
224
225 log_info("/* %s */", __func__);
226
227 rlimit_nofile_bump(-1);
228
229 max_fd = get_max_fd();
230 assert_se(max_fd > 10);
231
232 if (max_fd > 7000) {
233 /* If the worst fallback is activated we need to iterate through all possible fds, hence,
234 * let's lower the limit a small bit, so that we don't run for too long. Yes, this undoes the
235 * rlimit_nofile_bump() call above partially. */
236
237 (void) setrlimit_closest(RLIMIT_NOFILE, &(struct rlimit) { 7000, 7000 });
238 max_fd = 7000;
239 }
240
241 /* Try to use 5000 fds, but when we can't bump the rlimit to make that happen use the whole limit minus 10 */
242 n_fds = MIN(((size_t) max_fd & ~1U) - 10U, 5000U);
243 assert_se((n_fds & 1U) == 0U); /* make sure even number of fds */
244
245 /* Allocate the determined number of fds, always two at a time */
246 assert_se(fds = new(int, n_fds));
247 for (size_t i = 0; i < n_fds; i += 2)
248 assert_se(pipe2(fds + i, O_CLOEXEC) >= 0);
249
250 /* Validate this worked */
251 assert_se(validate_fds(true, fds, n_fds) == n_fds);
252
253 /* Randomized number of fds to keep, but at most every second */
254 n_keep = (random_u64() % (n_fds / 2));
255
256 /* Now randomly select a number of fds from the array above to keep */
257 assert_se(keep = new(int, n_keep));
258 for (size_t k = 0; k < n_keep; k++) {
259 for (;;) {
260 size_t p;
261
262 p = random_u64() % n_fds;
263 if (fds[p] >= 0) {
264 keep[k] = TAKE_FD(fds[p]);
265 break;
266 }
267 }
268 }
269
270 /* Check that all fds from both arrays are still open, and test how many in each are >= 0 */
271 assert_se(validate_fds(true, fds, n_fds) == n_fds - n_keep);
272 assert_se(validate_fds(true, keep, n_keep) == n_keep);
273
274 /* Close logging fd first, so that we don't confuse it by closing its fd */
275 log_close();
276 log_set_open_when_needed(true);
277
278 /* Close all but the ones to keep */
279 assert_se(close_all_fds(keep, n_keep) >= 0);
280
281 assert_se(validate_fds(false, fds, n_fds) == n_fds - n_keep);
282 assert_se(validate_fds(true, keep, n_keep) == n_keep);
283
284 /* Close everything else too! */
285 assert_se(close_all_fds(NULL, 0) >= 0);
286
287 assert_se(validate_fds(false, fds, n_fds) == n_fds - n_keep);
288 assert_se(validate_fds(false, keep, n_keep) == n_keep);
289
290 log_set_open_when_needed(false);
291 log_open();
292 }
293
seccomp_prohibit_close_range(void)294 static int seccomp_prohibit_close_range(void) {
295 #if HAVE_SECCOMP && defined(__SNR_close_range)
296 _cleanup_(seccomp_releasep) scmp_filter_ctx seccomp = NULL;
297 int r;
298
299 r = seccomp_init_for_arch(&seccomp, SCMP_ARCH_NATIVE, SCMP_ACT_ALLOW);
300 if (r < 0)
301 return log_warning_errno(r, "Failed to acquire seccomp context, ignoring: %m");
302
303 r = seccomp_rule_add_exact(
304 seccomp,
305 SCMP_ACT_ERRNO(EPERM),
306 SCMP_SYS(close_range),
307 0);
308 if (r < 0)
309 return log_warning_errno(r, "Failed to add close_range() rule, ignoring: %m");
310
311 r = seccomp_load(seccomp);
312 if (r < 0)
313 return log_warning_errno(r, "Failed to apply close_range() restrictions, ignoring: %m");
314
315 return 0;
316 #else
317 return log_warning_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Seccomp support or close_range() syscall definition not available.");
318 #endif
319 }
320
TEST(close_all_fds)321 TEST(close_all_fds) {
322 int r;
323
324 /* Runs the test four times. Once as is. Once with close_range() syscall blocked via seccomp, once
325 * with /proc overmounted, and once with the combination of both. This should trigger all fallbacks in
326 * the close_range_all() function. */
327
328 r = safe_fork("(caf-plain)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_LOG|FORK_WAIT, NULL);
329 if (r == 0) {
330 test_close_all_fds_inner();
331 _exit(EXIT_SUCCESS);
332 }
333 assert_se(r >= 0);
334
335 if (geteuid() != 0) {
336 log_notice("Lacking privileges, skipping running tests with blocked close_range() and with /proc/ overnmounted.");
337 return;
338 }
339
340 r = safe_fork("(caf-noproc)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_LOG|FORK_WAIT|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, NULL);
341 if (r == 0) {
342 r = mount_nofollow_verbose(LOG_WARNING, "tmpfs", "/proc", "tmpfs", 0, NULL);
343 if (r < 0)
344 log_notice("Overmounting /proc didn#t work, skipping close_all_fds() with masked /proc/.");
345 else
346 test_close_all_fds_inner();
347 _exit(EXIT_SUCCESS);
348 }
349 assert_se(r >= 0);
350
351 if (!is_seccomp_available()) {
352 log_notice("Seccomp not available, skipping seccomp tests in %s", __func__);
353 return;
354 }
355
356 r = safe_fork("(caf-seccomp)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_LOG|FORK_WAIT, NULL);
357 if (r == 0) {
358 r = seccomp_prohibit_close_range();
359 if (r < 0)
360 log_notice("Applying seccomp filter didn't work, skipping close_all_fds() test with masked close_range().");
361 else
362 test_close_all_fds_inner();
363
364 _exit(EXIT_SUCCESS);
365 }
366 assert_se(r >= 0);
367
368 r = safe_fork("(caf-scnp)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_LOG|FORK_WAIT|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE, NULL);
369 if (r == 0) {
370 r = seccomp_prohibit_close_range();
371 if (r < 0)
372 log_notice("Applying seccomp filter didn't work, skipping close_all_fds() test with masked close_range().");
373 else {
374 r = mount_nofollow_verbose(LOG_WARNING, "tmpfs", "/proc", "tmpfs", 0, NULL);
375 if (r < 0)
376 log_notice("Overmounting /proc didn#t work, skipping close_all_fds() with masked /proc/.");
377 else
378 test_close_all_fds_inner();
379 }
380
381 test_close_all_fds_inner();
382 _exit(EXIT_SUCCESS);
383 }
384 assert_se(r >= 0);
385 }
386
TEST(format_proc_fd_path)387 TEST(format_proc_fd_path) {
388 assert_se(streq_ptr(FORMAT_PROC_FD_PATH(0), "/proc/self/fd/0"));
389 assert_se(streq_ptr(FORMAT_PROC_FD_PATH(1), "/proc/self/fd/1"));
390 assert_se(streq_ptr(FORMAT_PROC_FD_PATH(2), "/proc/self/fd/2"));
391 assert_se(streq_ptr(FORMAT_PROC_FD_PATH(3), "/proc/self/fd/3"));
392 assert_se(streq_ptr(FORMAT_PROC_FD_PATH(2147483647), "/proc/self/fd/2147483647"));
393 }
394
TEST(fd_reopen)395 TEST(fd_reopen) {
396 _cleanup_close_ int fd1 = -1, fd2 = -1;
397 struct stat st1, st2;
398 int fl;
399
400 /* Test this with a directory */
401 fd1 = open("/proc", O_DIRECTORY|O_PATH|O_CLOEXEC);
402 assert_se(fd1 >= 0);
403
404 assert_se(fstat(fd1, &st1) >= 0);
405 assert_se(S_ISDIR(st1.st_mode));
406
407 fl = fcntl(fd1, F_GETFL);
408 assert_se(fl >= 0);
409 assert_se(FLAGS_SET(fl, O_DIRECTORY));
410 assert_se(FLAGS_SET(fl, O_PATH));
411
412 fd2 = fd_reopen(fd1, O_RDONLY|O_DIRECTORY|O_CLOEXEC); /* drop the O_PATH */
413 assert_se(fd2 >= 0);
414
415 assert_se(fstat(fd2, &st2) >= 0);
416 assert_se(S_ISDIR(st2.st_mode));
417 assert_se(st1.st_ino == st2.st_ino);
418 assert_se(st1.st_rdev == st2.st_rdev);
419
420 fl = fcntl(fd2, F_GETFL);
421 assert_se(fl >= 0);
422 assert_se(FLAGS_SET(fl, O_DIRECTORY));
423 assert_se(!FLAGS_SET(fl, O_PATH));
424
425 safe_close(fd1);
426
427 fd1 = fd_reopen(fd2, O_DIRECTORY|O_PATH|O_CLOEXEC); /* reacquire the O_PATH */
428 assert_se(fd1 >= 0);
429
430 assert_se(fstat(fd1, &st1) >= 0);
431 assert_se(S_ISDIR(st1.st_mode));
432 assert_se(st1.st_ino == st2.st_ino);
433 assert_se(st1.st_rdev == st2.st_rdev);
434
435 fl = fcntl(fd1, F_GETFL);
436 assert_se(fl >= 0);
437 assert_se(FLAGS_SET(fl, O_DIRECTORY));
438 assert_se(FLAGS_SET(fl, O_PATH));
439
440 safe_close(fd1);
441
442 /* And now, test this with a file. */
443 fd1 = open("/proc/version", O_PATH|O_CLOEXEC);
444 assert_se(fd1 >= 0);
445
446 assert_se(fstat(fd1, &st1) >= 0);
447 assert_se(S_ISREG(st1.st_mode));
448
449 fl = fcntl(fd1, F_GETFL);
450 assert_se(fl >= 0);
451 assert_se(!FLAGS_SET(fl, O_DIRECTORY));
452 assert_se(FLAGS_SET(fl, O_PATH));
453
454 assert_se(fd_reopen(fd1, O_RDONLY|O_DIRECTORY|O_CLOEXEC) == -ENOTDIR);
455 fd2 = fd_reopen(fd1, O_RDONLY|O_CLOEXEC); /* drop the O_PATH */
456 assert_se(fd2 >= 0);
457
458 assert_se(fstat(fd2, &st2) >= 0);
459 assert_se(S_ISREG(st2.st_mode));
460 assert_se(st1.st_ino == st2.st_ino);
461 assert_se(st1.st_rdev == st2.st_rdev);
462
463 fl = fcntl(fd2, F_GETFL);
464 assert_se(fl >= 0);
465 assert_se(!FLAGS_SET(fl, O_DIRECTORY));
466 assert_se(!FLAGS_SET(fl, O_PATH));
467
468 safe_close(fd1);
469
470 assert_se(fd_reopen(fd2, O_DIRECTORY|O_PATH|O_CLOEXEC) == -ENOTDIR);
471 fd1 = fd_reopen(fd2, O_PATH|O_CLOEXEC); /* reacquire the O_PATH */
472 assert_se(fd1 >= 0);
473
474 assert_se(fstat(fd1, &st1) >= 0);
475 assert_se(S_ISREG(st1.st_mode));
476 assert_se(st1.st_ino == st2.st_ino);
477 assert_se(st1.st_rdev == st2.st_rdev);
478
479 fl = fcntl(fd1, F_GETFL);
480 assert_se(fl >= 0);
481 assert_se(!FLAGS_SET(fl, O_DIRECTORY));
482 assert_se(FLAGS_SET(fl, O_PATH));
483
484 /* Also check the right error is generated if the fd is already closed */
485 safe_close(fd1);
486 assert_se(fd_reopen(fd1, O_RDONLY|O_CLOEXEC) == -EBADF);
487 fd1 = -1;
488 }
489
TEST(take_fd)490 TEST(take_fd) {
491 _cleanup_close_ int fd1 = -1, fd2 = -1;
492 int array[2] = { -1, -1 }, i = 0;
493
494 assert_se(fd1 == -1);
495 assert_se(fd2 == -1);
496
497 fd1 = eventfd(0, EFD_CLOEXEC);
498 assert_se(fd1 >= 0);
499
500 fd2 = TAKE_FD(fd1);
501 assert_se(fd1 == -1);
502 assert_se(fd2 >= 0);
503
504 assert_se(array[0] == -1);
505 assert_se(array[1] == -1);
506
507 array[0] = TAKE_FD(fd2);
508 assert_se(fd1 == -1);
509 assert_se(fd2 == -1);
510 assert_se(array[0] >= 0);
511 assert_se(array[1] == -1);
512
513 array[1] = TAKE_FD(array[i]);
514 assert_se(array[0] == -1);
515 assert_se(array[1] >= 0);
516
517 i = 1 - i;
518 array[0] = TAKE_FD(*(array + i));
519 assert_se(array[0] >= 0);
520 assert_se(array[1] == -1);
521
522 i = 1 - i;
523 fd1 = TAKE_FD(array[i]);
524 assert_se(fd1 >= 0);
525 assert_se(array[0] == -1);
526 assert_se(array[1] == -1);
527 }
528
529 DEFINE_TEST_MAIN(LOG_DEBUG);
530