Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2ac92d5dd | ||
|
|
b78b7073ce |
No files matched your search
@@ -1161,6 +1161,7 @@ int system(const char *command) {
|
||||
|
||||
int status = -1;
|
||||
pid_t pid = start_shell(command, -1, -1, &old, &intr, &quit, 0);
|
||||
if (pid < 0) status = 127 << 8; // as glibc's system() when the shell could not be started
|
||||
if (pid > 0) {
|
||||
while (waitpid(pid, &status, 0) < 0) {
|
||||
if (errno != EINTR) {
|
||||
@@ -1192,28 +1193,52 @@ static pthread_mutex_t g_popen_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static pid_t start_shell(const char *command, int child_fd, int target_fd, const sigset_t *mask,
|
||||
const struct sigaction *intr, const struct sigaction *quit, int close_popen_streams) {
|
||||
pid_t pid = fork();
|
||||
if (pid != 0) return pid;
|
||||
if (intr) sigaction(SIGINT, intr, NULL);
|
||||
if (quit) sigaction(SIGQUIT, quit, NULL);
|
||||
if (mask) sigprocmask(SIG_SETMASK, mask, NULL);
|
||||
// Through posix_spawn(), as glibc does: its child only makes system calls. A forked child running
|
||||
// the exec code here would take locks that another thread of a multithreaded caller may have held
|
||||
// at fork(), and wait for them forever (Steam's popen()s did, and its main loop stalled).
|
||||
posix_spawn_file_actions_t actions;
|
||||
posix_spawnattr_t attr;
|
||||
if (posix_spawn_file_actions_init(&actions) != 0) return -1;
|
||||
if (posix_spawnattr_init(&attr) != 0) {
|
||||
posix_spawn_file_actions_destroy(&actions);
|
||||
return -1;
|
||||
}
|
||||
int err = 0;
|
||||
if (child_fd >= 0) {
|
||||
if (child_fd == target_fd) {
|
||||
fcntl(target_fd, F_SETFD, 0);
|
||||
} else if (dup2(child_fd, target_fd) < 0) {
|
||||
_exit(127);
|
||||
}
|
||||
// dup2 onto itself clears FD_CLOEXEC in the child (glibc 2.29 and later)
|
||||
err = posix_spawn_file_actions_adddup2(&actions, child_fd, target_fd);
|
||||
}
|
||||
// POSIX: the streams of earlier popen() calls are not open in the new shell
|
||||
if (close_popen_streams) {
|
||||
for (struct ddnatv_popen *p = g_popen_streams; p; p = p->next) {
|
||||
int fd = fileno(p->fp);
|
||||
if (fd >= 0 && fd != target_fd) close(fd);
|
||||
}
|
||||
for (struct ddnatv_popen *p = g_popen_streams; !err && close_popen_streams && p; p = p->next) {
|
||||
int fd = fileno(p->fp);
|
||||
if (fd >= 0 && fd != target_fd) err = posix_spawn_file_actions_addclose(&actions, fd);
|
||||
}
|
||||
short flags = 0;
|
||||
if (!err && mask) {
|
||||
posix_spawnattr_setsigmask(&attr, mask);
|
||||
flags |= POSIX_SPAWN_SETSIGMASK;
|
||||
}
|
||||
// SIGINT and SIGQUIT as they were before system() ignored them: an exec keeps an ignored signal
|
||||
// ignored and puts a handled one back to the default
|
||||
sigset_t defaults;
|
||||
sigemptyset(&defaults);
|
||||
if (intr && intr->sa_handler != SIG_IGN) sigaddset(&defaults, SIGINT);
|
||||
if (quit && quit->sa_handler != SIG_IGN) sigaddset(&defaults, SIGQUIT);
|
||||
if (!err && (intr || quit)) {
|
||||
posix_spawnattr_setsigdefault(&attr, &defaults);
|
||||
flags |= POSIX_SPAWN_SETSIGDEF;
|
||||
}
|
||||
if (!err) err = posix_spawnattr_setflags(&attr, flags);
|
||||
pid_t pid = -1;
|
||||
char *const argv[] = { (char *)"sh", (char *)"-c", (char *)command, NULL };
|
||||
ddnatv_execve("/bin/sh", argv, environ, 0);
|
||||
_exit(127);
|
||||
if (!err) err = posix_spawn(&pid, "/bin/sh", &actions, &attr, argv, environ);
|
||||
posix_spawn_file_actions_destroy(&actions);
|
||||
posix_spawnattr_destroy(&attr);
|
||||
if (err) {
|
||||
errno = err;
|
||||
return -1;
|
||||
}
|
||||
return pid;
|
||||
}
|
||||
|
||||
FILE *popen(const char *command, const char *type) {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from tools.tests.test_usr2_preload import runner
|
||||
|
||||
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
|
||||
|
||||
# The rootfs' /bin/sh for these tests: "sh -c 'echo WORDS'" prints WORDS, "sh -c 'exit N'" exits N.
|
||||
SHELL = r"""
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 3 || strcmp(argv[1], "-c") != 0) return 2;
|
||||
if (strncmp(argv[2], "echo ", 5) == 0) {
|
||||
puts(argv[2] + 5);
|
||||
return 0;
|
||||
}
|
||||
if (strncmp(argv[2], "exit ", 5) == 0) return atoi(argv[2] + 5);
|
||||
return 127;
|
||||
}
|
||||
"""
|
||||
|
||||
# popen() and system() through the hook (which starts the shell with posix_spawn())
|
||||
PROGRAM = r"""
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (strcmp(argv[1], "system") == 0) {
|
||||
int status = system("exit 3");
|
||||
printf("system\t%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
||||
return 0;
|
||||
}
|
||||
// a second stream open while the first is read: the shell of the first must not hold it
|
||||
FILE *other = popen("echo other", "r");
|
||||
FILE *f = popen("echo from the shell", "r");
|
||||
char line[64] = "";
|
||||
if (f && !fgets(line, sizeof(line), f)) line[0] = 0;
|
||||
line[strcspn(line, "\n")] = 0;
|
||||
int status = f ? pclose(f) : -1;
|
||||
if (other) pclose(other);
|
||||
printf("popen\t%s\n", line);
|
||||
printf("pclose\t%d\n", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class NativeHookPopenTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
|
||||
tmp = Path(cls.tmp.name)
|
||||
cls.hook = tmp / "hook.so"
|
||||
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
|
||||
cls.root = tmp / "root"
|
||||
(cls.root / "bin").mkdir(parents=True)
|
||||
(tmp / "sh.c").write_text(SHELL)
|
||||
subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/sh"), str(tmp / "sh.c")], check=True)
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
cls.program = tmp / "prog"
|
||||
subprocess.run([cls.cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c")], check=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_program(self, mode):
|
||||
hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)}
|
||||
env = {k: v for k, v in os.environ.items() if k not in hook_env}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
|
||||
else:
|
||||
cmd = []
|
||||
env.update(hook_env)
|
||||
out = subprocess.run(cmd + [str(self.program), mode], env=env, capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
return dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out
|
||||
|
||||
def test_popen_reads_the_shells_output(self):
|
||||
result, out = self.run_program("popen")
|
||||
self.assertEqual("from the shell", result.get("popen"), out.stdout + out.stderr)
|
||||
self.assertEqual("0", result.get("pclose"), out.stdout)
|
||||
|
||||
def test_system_returns_the_shells_status(self):
|
||||
result, out = self.run_program("system")
|
||||
self.assertEqual("3", result.get("system"), out.stdout + out.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user