From 64df54791686059374951f59c1b5c68d6f1f5e8d Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Fri, 9 Feb 2018 17:53:28 +0100 Subject: fd-util: move certain fds above fd #2 (#8129) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This adds some paranoia code that moves some of the fds we allocate for longer periods of times to fds > 2 if they are allocated below this boundary. This is a paranoid safety thing, in order to avoid that external code might end up erroneously use our fds under the assumption they were valid stdin/stdout/stderr. Think: some app closes stdin/stdout/stderr and then invokes 'fprintf(stderr, …' which causes writes on our fds. This both adds the helper to do the moving as well as ports over a number of users to this new logic. Since we don't want to litter all our code with invocations of this I tried to strictly focus on fds we keep open for long periods of times only and only in code that is frequently loaded into foreign programs (under the assumptions that in our own codebase we are smart enough to always keep stdin/stdout/stderr allocated to avoid this pitfall). Specifically this means all code used by NSS and our sd-xyz API: 1. our logging APIs 2. sd-event 3. sd-bus 4. sd-resolve 5. sd-netlink This changed was inspired by this: https://github.com/systemd/systemd/issues/8075#issuecomment-363689755 This shows that apparently IRL there are programs that do close stdin/stdout/stderr, and we should accomodate for that. Note that this won't fix any bugs, this just makes sure that buggy programs are less likely to interfere with out own code. --- src/test/test-fd-util.c | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'src/test/test-fd-util.c') diff --git a/src/test/test-fd-util.c b/src/test/test-fd-util.c index 6b611b4b9..76b36053b 100644 --- a/src/test/test-fd-util.c +++ b/src/test/test-fd-util.c @@ -157,6 +157,24 @@ static void test_acquire_data_fd(void) { test_acquire_data_fd_one(ACQUIRE_NO_DEV_NULL|ACQUIRE_NO_MEMFD|ACQUIRE_NO_PIPE|ACQUIRE_NO_TMPFILE); } +static void test_fd_move_above_stdio(void) { + int original_stdin, new_fd; + + original_stdin = fcntl(0, F_DUPFD, 3); + assert_se(original_stdin >= 3); + assert_se(close_nointr(0) != EBADF); + + new_fd = open("/dev/null", O_RDONLY); + assert_se(new_fd == 0); + + new_fd = fd_move_above_stdio(new_fd); + assert_se(new_fd >= 3); + + assert_se(dup(original_stdin) == 0); + assert_se(close_nointr(original_stdin) != EBADF); + assert_se(close_nointr(new_fd) != EBADF); +} + int main(int argc, char *argv[]) { test_close_many(); test_close_nointr(); @@ -165,6 +183,7 @@ int main(int argc, char *argv[]) { #endif // 0 test_open_serialization_fd(); test_acquire_data_fd(); + test_fd_move_above_stdio(); return 0; } -- cgit v1.2.3