8000 logs: keep duplicated log fds above stderr and open log files write-only by hyc-alt · Pull Request #414 · google/nsjail · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ endif

BIN = nsjail
LIBS = kafel/libkafel.a
TEST_BINS = tests/util_msg_test tests/nstun_buffer_budget_test tests/nstun_flow_limit_test tests/nstun_policy_test tests/nstun_ip_test tests/nstun_udp_peer_test tests/nstun_encap_test tests/nstun_tcp_capacity_test tests/mount_source_anchor_test tests/mount_staging_unbindable_test tests/mnt_options_test tests/unotify_syscall_test tests/unotify_stats_test
TEST_BINS = tests/util_msg_test tests/logs_fd_test tests/nstun_buffer_budget_test tests/nstun_flow_limit_test tests/nstun_policy_test tests/nstun_ip_test tests/nstun_udp_peer_test tests/nstun_encap_test tests/nstun_tcp_capacity_test tests/mount_source_anchor_test tests/mount_staging_unbindable_test tests/mnt_options_test tests/unotify_syscall_test tests/unotify_stats_test

# If PASTA_BIN_PATH is not provided in env, dynamically search for it if EMBED_PASTA is requested
# or fallback to it naturally.
Expand Down Expand Up @@ -177,6 +177,7 @@ tests/mount_staging_unbindable_test: tests/mount_staging_unbindable_test.c

test: $(BIN) $(TEST_BINS) test-cmdline test-newapi-recursive-readonly test-mnt-dst-symlink test-mnt-prefix-env test-nstun-tcp-capacity
$(call run_test, ./tests/util_msg_test, 0)
$(call run_test, ./tests/logs_fd_test, 0)
$(call run_test, ./tests/nstun_buffer_budget_test, 0)
$(call run_test, ./tests/nstun_flow_limit_test, 0)
$(call run_test, ./tests/nstun_policy_test, 0)
Expand Down Expand Up @@ -311,6 +312,9 @@ endif
tests/util_msg_test: tests/util_msg_test.cc util.cc util.h logs.cc $(SRCS_PB_CXX) $(SRCS_PB_H)
$(CXX) $(filter-out -c,$(CXXFLAGS)) tests/util_msg_test.cc util.cc logs.cc $(SRCS_PB_CXX) -o $@ $(LDFLAGS)

tests/logs_fd_test: tests/logs_fd_test.cc logs.cc logs.h util.cc util.h $(SRCS_PB_CXX) $(SRCS_PB_H)
$(CXX) $(filter-out -c,$(CXXFLAGS)) tests/logs_fd_test.cc logs.cc util.cc $(SRCS_PB_CXX) -o $@ $(LDFLAGS)

test-nstun-tcp-capacity: tests/nstun_tcp_capacity_test
@./tests/nstun_tcp_capacity_test; rc=$$?; \
if [ "$$rc" -eq 77 ]; then \
Expand Down
19 changes: 12 additions & 7 deletions logs.cc
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,14 @@ static bool fdIsatty(int fd) {

static void setDupLogFdOr(int fd, int orfd) {
int saved_errno = errno;
_log_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
_log_fd = TEMP_FAILURE_RETRY(fcntl(fd, F_DUPFD_CLOEXEC, STDERR_FILENO + 1));
if (_log_fd == -1) {
_log_fd = fcntl(orfd, F_DUPFD_CLOEXEC, 0);
_log_fd = TEMP_FAILURE_RETRY(fcntl(orfd, F_DUPFD_CLOEXEC, STDERR_FILENO + 1));
}
if (_log_fd == -1) {
if (_log_fd == -1 && errno != EBADF) {
_log_fd = orfd;
}
_log_fd_isatty = fdIsatty(_log_fd);
_log_fd_isatty = (_log_fd >= 0) && fdIsatty(_log_fd);
errno = saved_errno;
}

Expand All @@ -74,6 +74,10 @@ static void updateStderrFdDistinct(void) {
_log_stderr_fd_distinct = false;
return;
}
if (_log_fd == -1) {
_log_stderr_fd_distinct = true;
return;
}
struct stat st_log, st_err;
if (fstat(_log_fd, &st_log) == -1 || fstat(_log_stderr_fd, &st_err) == -1) {
_log_stderr_fd_distinct = true;
Expand Down Expand Up @@ -115,7 +119,8 @@ enum llevel_t getLogLevel(void) {
bool setLogStderrLevel(enum llevel_t ll) {
_log_stderr_level = ll;
if (_log_stderr_fd == -1) {
_log_stderr_fd = TEMP_FAILURE_RETRY(fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0));
_log_stderr_fd =
TEMP_FAILURE_RETRY(fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, STDERR_FILENO + 1));
if (_log_stderr_fd == -1) {
if (errno == EBADF) {
PLOG_W("stderr is closed, log_stderr_level disabled");
Expand Down Expand Up @@ -145,7 +150,7 @@ void logFile(const std::string& log_file, int log_fd) {
int newlogfd = -1;
if (!log_file.empty()) {
newlogfd = TEMP_FAILURE_RETRY(
open(log_file.c_str(), O_CREAT | O_RDWR | O_APPEND | O_CLOEXEC | O_NOFOLLOW,
open(log_file.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC | O_NOFOLLOW,
0640));
if (newlogfd == -1) {
PLOG_W("Couldn't open('%s')", log_file.c_str());
Expand Down Expand Up @@ -242,7 +247,7 @@ void logMsg(enum llevel_t ll, const char* fn, int ln, bool perr, const char* fmt
}
/* End printing logs */

if (to_main) {
if (to_main && _log_fd >= 0) {
writeLogMsg(_log_fd, _log_fd_isatty, logLevels[ll].prefix, msg);
}
if (to_stderr) {
Expand Down
280 changes: 280 additions & 0 deletions tests/logs_fd_test.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,280 @@
#include <assert.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

#include <string>

#include "logs.h"

namespace {

size_t countOpenFds() {
DIR* dir = opendir("/proc/self/fd");
assert(dir != nullptr);
size_t count = 0;
while (const auto* entry = readdir(dir)) {
if (entry->d_name[0] != '.') {
count++;
}
}
closedir(dir);
return count;
}

void assertFdClosed(int fd) {
errno = 0;
assert(fcntl(fd, F_GETFD) == -1 && errno == EBADF);
}

void assertFdCloexec(int fd) {
int flags = fcntl(fd, F_GETFD);
assert(flags != -1 && (flags & FD_CLOEXEC) != 0);
}

std::string readFile(const std::string& path) {
int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
assert(fd >= 0);
std::string out;
char buf[512];
for (;;) {
ssize_t n = read(fd, buf, sizeof(buf));
assert(n >= 0);
if (n == 0) {
break;
}
out.append(buf, static_cast<size_t>(n));
}
close(fd);
return out;
}

template <typename Fn>
void runInChild(const char* name, Fn fn) {
fflush(nullptr);
pid_t pid = fork();
assert(pid >= 0);
if (pid == 0) {
fn();
_exit(0);
}
int status = 0;
assert(waitpid(pid, &status, 0) == pid);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
fprintf(stderr, "FAIL: %s (status=0x%x)\n", name, status);
exit(1);
}
}

void testLogFileClosedStdinStderr(const std::string& log_path) {
assert(close(STDIN_FILENO) == 0);
assert(close(STDERR_FILENO) == 0);

logs::logFile(log_path, STDERR_FILENO);
int lfd = logs::logFd();
assert(lfd > STDERR_FILENO);
assertFdCloexec(lfd);
int fl = fcntl(lfd, F_GETFL);
assert(fl != -1 && (fl & O_ACCMODE) == O_WRONLY && (fl & O_APPEND) != 0);
assertFdClosed(STDIN_FILENO);
assertFdClosed(STDERR_FILENO);
}

void testLogFileAllStdioClosed(const std::string& log_path) {
assert(close(STDIN_FILENO) == 0);
assert(close(STDOUT_FILENO) == 0);
assert(close(STDERR_FILENO) == 0);

logs::logFile(log_path, STDERR_FILENO);
int lfd = logs::logFd();
assert(lfd > STDERR_FILENO);
assertFdCloexec(lfd);
int fl = fcntl(lfd, F_GETFL);
assert(fl != -1 && (fl & O_ACCMODE) == O_WRONLY);
assertFdClosed(STDIN_FILENO);
assertFdClosed(STDOUT_FILENO);
assertFdClosed(STDERR_FILENO);
}

void testLogFdClosedStdinStdout(const std::string& log_path) {
int raw_fd = open(log_path.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0640);
assert(raw_fd > STDERR_FILENO);
assert(close(STDIN_FILENO) == 0);
assert(close(STDOUT_FILENO) == 0);

logs::logFile("", raw_fd);
int lfd = logs::logFd();
assert(lfd > STDERR_FILENO);
assert(lfd != raw_fd);
assertFdCloexec(lfd);
assertFdClosed(STDIN_FILENO);
assertFdClosed(STDOUT_FILENO);
close(raw_fd);
}

void testLogStderrLevelDoesNotOccupyStdio(
const std::string& log_path, const std::string& err_path, bool stderr_first) {
int err_fd = open(err_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC | O_CLOEXEC, 0640);
assert(err_fd >= 0);
assert(dup2(err_fd, STDERR_FILENO) == STDERR_FILENO);
close(err_fd);

assert(close(STDIN_FILENO) == 0);
assert(close(STDOUT_FILENO) == 0);

if (stderr_first) {
assert(logs::setLogStderrLevel(logs::INFO));
logs::logFile(log_path, STDERR_FILENO);
} else {
logs::logFile(log_path, STDERR_FILENO);
assert(logs::setLogStderrLevel(logs::INFO));
}

assert(logs::logFd() > STDERR_FILENO);
assertFdCloexec(logs::logFd());
assertFdClosed(STDIN_FILENO);
assertFdClosed(STDOUT_FILENO);

int client_pipe[2];
assert(pipe2(client_pipe, O_CLOEXEC) == 0);
int read_end = fcntl(client_pipe[0], F_DUPFD_CLOEXEC, STDERR_FILENO + 1);
assert(read_end > STDERR_FILENO);
close(client_pipe[0]);
if (client_pipe[1] != STDOUT_FILENO) {
assert(dup2(client_pipe[1], STDOUT_FILENO) == STDOUT_FILENO);
close(client_pipe[1]);
}

lo 10BC8 gs::setLogLevel(logs::INFO);
LOG_I("LOGS_FD_TEST_MARKER");
close(STDOUT_FILENO);

char buf[64];
ssize_t n = read(read_end, buf, sizeof(buf));
close(read_end);
assert(n == 0);

logs::closeLogStderr();
}

void testRepeatedLogFileDoesNotLeak(const std::string& log_path) {
assert(close(STDIN_FILENO) == 0);
assert(close(STDOUT_FILENO) == 0);

logs::logFile(log_path, STDERR_FILENO);
size_t baseline = countOpenFds();
for (int i = 0; i < 8; i++) {
logs::logFile(log_path, STDERR_FILENO);
assert(logs::logFd() > STDERR_FILENO);
assertFdClosed(STDIN_FILENO);
assertFdClosed(STDOUT_FILENO);
}
assert(countOpenFds() == baseline);
}

void testClosedFallbackDoesNotReuseStdio() {
assert(close(STDERR_FILENO) == 0);
logs::logFile("", STDERR_FILENO);
assert(logs::logFd() == -1);
assertFdClosed(STDERR_FILENO);

int client_pipe[2];
assert(pipe2(client_pipe, O_CLOEXEC) == 0);
int read_end = fcntl(client_pipe[0], F_DUPFD_CLOEXEC, STDERR_FILENO + 1);
assert(read_end > STDERR_FILENO);
close(client_pipe[0]);
if (client_pipe[1] != STDERR_FILENO) {
assert(dup2(client_pipe[1], STDERR_FILENO) == STDERR_FILENO);
close(client_pipe[1]);
}

logs::setLogLevel(logs::INFO);
LOG_I("SHOULD_NOT_WRITE_TO_REUSED_STDERR");
close(STDERR_FILENO);

char buf[64];
ssize_t n = read(read_end, buf, sizeof(buf));
close(read_end);
assert(n == 0);
}

void testFatalStillExitsWhenLogDisabled() {
fflush(nullptr);
pid_t pid = fork();
assert(pid >= 0);
if (pid == 0) {
assert(close(STDERR_FILENO) == 0);
logs::logFile("", STDERR_FILENO);
assert(logs::logFd() == -1);
LOG_F("fatal with closed stderr");
_exit(0);
}
int status = 0;
assert(waitpid(pid, &status, 0) == pid);
assert(WIFEXITED(status) && WEXITSTATUS(status) == 0xff);
}

} // namespace

int main(int argc, char** argv) {
if (argc == 2 && strcmp(argv[1], "--check-ctor") == 0) {
assert(logs::logFd() > STDERR_FILENO);
assertFdCloexec(logs::logFd());
assertFdClosed(STDIN_FILENO);
assertFdClosed(STDOUT_FILENO);
return 0;
}

runInChild("ctor_closed_stdin_stdout", [&]() {
assert(close(STDIN_FILENO) == 0);
assert(close(STDOUT_FILENO) == 0);
execl("/proc/self/exe", argv[0], "--check-ctor", nullptr);
_exit(127);
});

char dir_tmpl[] = "/tmp/nsjail-logs-fd-test.XXXXXX";
char* dir = mkdtemp(dir_tmpl);
assert(dir != nullptr);
std::string base(dir);
std::string log1 = base + "/log1";
std::string log2 = base + "/log2";
std::string log3 = base + "/log3";
std::string log4 = base + "/log4";
std::string err4 = base + "/err4";
std::string log5 = base + "/log5";
std::string err5 = base + "/err5";

runInChild("closed_stdin_stderr", [&]() { testLogFileClosedStdinStderr(log1); });
runInChild("all_stdio_closed", [&]() { testLogFileAllStdioClosed(log2); });
runInChild("log_fd_closed_stdin_stdout", [&]() { testLogFdClosedStdinStdout(log3); });
runInChild("stderr_level_after_logfile",
[&]() { testLogStderrLevelDoesNotOccupyStdio(log4, err4, /* stderr_first= */ false); });
assert(readFile(log4).find("LOGS_FD_TEST_MARKER") != std::string::npos);
assert(readFile(err4).find("LOGS_FD_TEST_MARKER") != std::string::npos);

runInChild("stderr_level_before_logfile",
[&]() { testLogStderrLevelDoesNotOccupyStdio(log5, err5, /* stderr_first= */ true); });
assert(readFile(log5).find("LOGS_FD_TEST_MARKER") != std::string::npos);
assert(readFile(err5).find("LOGS_FD_TEST_MARKER") != std::string::npos);

runInChild("repeated_logfile_no_leak", [&]() { testRepeatedLogFileDoesNotLeak(log1); });
runInChild("closed_fallback_no_reuse", []() { testClosedFallbackDoesNotReuseStdio(); });
testFatalStillExitsWhenLogDisabled();

unlink(log1.c_str());
unlink(log2.c_str());
unlink(log3.c_str());
unlink(log4.c_str());
unlink(err4.c_str());
unlink(log5.c_str());
unlink(err5.c_str());
rmdir(base.c_str());

puts("logs_fd_test: passed");
return 0;
}
0