diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index 555ce7fc21..5bf75ae4aa 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -712,81 +712,82 @@ int execle(const char *path, const char *arg0, ...) { return ret; } -int execvp(const char *file, char *const argv[]) { +static int exec_or_script(const char *path, char *const argv[], char *const envp[]) { + execve(path, argv, envp); + if (errno != ENOEXEC) return -1; + int argc = 0; + while (argv && argv[argc]) argc++; + char **script = (char **)malloc(sizeof(char *) * (size_t)(argc + 3)); + if (!script) { + errno = ENOMEM; + return -1; + } + script[0] = (char *)"/bin/sh"; + script[1] = (char *)path; + int n = 2; + for (int i = 1; i < argc; i++) script[n++] = argv[i]; + script[n] = NULL; + execve(script[0], script, envp); + int saved_errno = errno; + free(script); + errno = saved_errno; + return -1; +} + +static int exec_search_dir(const char *dir, size_t len, const char *file, char *const argv[], char *const envp[], int *denied) { + char candidate[PATH_MAX]; + int n = len ? snprintf(candidate, sizeof(candidate), "%.*s/%s", (int)len, dir, file) + : snprintf(candidate, sizeof(candidate), "%s", file); + if (n < 0 || n >= (int)sizeof(candidate)) { + errno = ENAMETOOLONG; + return 0; + } + exec_or_script(candidate, argv, envp); + switch (errno) { + case EACCES: + *denied = 1; + return 0; + case ENOENT: case ENOTDIR: case ESTALE: case ENODEV: case ETIMEDOUT: case ENAMETOOLONG: + return 0; + default: + return 1; + } +} + +static int exec_search(const char *file, char *const argv[], char *const envp[], const char *path_env) { if (!file || !*file) { errno = ENOENT; return -1; } - if (strchr(file, '/')) { - return execve(file, argv, environ); - } - const char *path_env = getenv("PATH"); + if (strchr(file, '/')) return exec_or_script(file, argv, envp); if (!path_env) path_env = "/usr/bin:/bin"; - char path_copy[4096]; - strncpy(path_copy, path_env, sizeof(path_copy) - 1); - path_copy[sizeof(path_copy) - 1] = '\0'; - char *saveptr = NULL; - char *token = strtok_r(path_copy, ":", &saveptr); - while (token) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", token, file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, environ); - } - token = strtok_r(NULL, ":", &saveptr); + int denied = 0; + for (const char *p = path_env;; ) { + const char *end = strchrnul(p, ':'); + if (exec_search_dir(p, (size_t)(end - p), file, argv, envp, &denied)) return -1; + if (!*end) break; + p = end + 1; } - const char *standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin", NULL}; - for (int i = 0; standard_paths[i] != NULL; i++) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", standard_paths[i], file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, environ); - } - } - return execve(file, argv, environ); + static const char *const standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin"}; + for (size_t i = 0; i < sizeof(standard_paths) / sizeof(standard_paths[0]); i++) + if (exec_search_dir(standard_paths[i], strlen(standard_paths[i]), file, argv, envp, &denied)) return -1; + errno = denied ? EACCES : ENOENT; + return -1; +} + +int execvp(const char *file, char *const argv[]) { + return exec_search(file, argv, environ, getenv("PATH")); } int execvpe(const char *file, char *const argv[], char *const envp[]) { - if (!file || !*file) { - errno = ENOENT; - return -1; - } - if (strchr(file, '/')) { - return execve(file, argv, envp); - } const char *path_env = NULL; - if (envp) { - for (char *const *ep = envp; *ep; ep++) { - if (strncmp(*ep, "PATH=", 5) == 0) { - path_env = *ep + 5; - break; - } + for (char *const *ep = envp; ep && *ep; ep++) { + if (strncmp(*ep, "PATH=", 5) == 0) { + path_env = *ep + 5; + break; } } - if (!path_env) path_env = getenv("PATH"); - if (!path_env) path_env = "/usr/bin:/bin"; - char path_copy[4096]; - strncpy(path_copy, path_env, sizeof(path_copy) - 1); - path_copy[sizeof(path_copy) - 1] = '\0'; - char *saveptr = NULL; - char *token = strtok_r(path_copy, ":", &saveptr); - while (token) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", token, file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, envp); - } - token = strtok_r(NULL, ":", &saveptr); - } - const char *standard_paths[] = {"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/usr/local/bin", NULL}; - for (int i = 0; standard_paths[i] != NULL; i++) { - char candidate[PATH_MAX]; - snprintf(candidate, sizeof(candidate), "%s/%s", standard_paths[i], file); - if (access(candidate, F_OK) == 0) { - return execve(candidate, argv, envp); - } - } - return execve(file, argv, envp); + return exec_search(file, argv, envp, path_env ? path_env : getenv("PATH")); } typedef int (*orig_posix_spawn_f_type)(pid_t *, const char *, const posix_spawn_file_actions_t *, diff --git a/tools/tests/test_native_hook_execvp.py b/tools/tests/test_native_hook_execvp.py new file mode 100644 index 0000000000..6fa37c4664 --- /dev/null +++ b/tools/tests/test_native_hook_execvp.py @@ -0,0 +1,140 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +RECORDER = r""" +#include +#include +#include +#include +#include + +int execve(const char *path, char *const argv[], char *const envp[]) { + if (access(path, F_OK) != 0) { errno = ENOENT; return -1; } + if (access(path, X_OK) != 0) { errno = EACCES; return -1; } + char head[2] = {0}; + int fd = open(path, O_RDONLY); + if (fd >= 0) { if (read(fd, head, 2) < 0) head[0] = 0; close(fd); } + if (memcmp(head, "#!", 2) != 0 && memcmp(head, "\177E", 2) != 0) { + errno = ENOEXEC; + return -1; + } + printf("call"); + for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]); + printf("\n"); + fflush(stdout); + _exit(0); +} +""" + +PROBE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include + +int main(int argc, char **argv) { + int ret; + if (strcmp(argv[1], "vpe") == 0) { + char path[4096]; + snprintf(path, sizeof(path), "PATH=%s", argv[2]); + char *envp[] = {path, NULL}; + ret = execvpe(argv[3], argv + 3, envp); + } else { + ret = execvp(argv[2], argv + 2); + } + printf("ret\t%d\t%s\n", ret, strerror(errno)); + return 1; +} +""" + + +class NativeHookExecvpTest(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) + (tmp / "recorder.c").write_text(RECORDER) + cls.recorder = tmp / "recorder.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + cls.dirs = Path("/opt/probe") + for name in ("bin", "opt/probe/locked", "opt/probe/open", "opt/probe/work"): + (cls.root / name).mkdir(parents=True) + (tmp / "sh.c").write_text("int main(void) { return 0; }\n") + subprocess.run([cls.cc, "-static", "-O1", "-o", str(cls.root / "bin/sh"), str(tmp / "sh.c")], check=True) + cls.script("locked/tool", 0o644) + cls.script("open/tool", 0o755, "#!/bin/sh\n") + cls.script("open/plain", 0o755) + cls.script("work/here", 0o755) + + @classmethod + def script(cls, name, mode, text="echo plain\n"): + path = cls.root / "opt/probe" / name + path.write_text(text) + path.chmod(mode) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def call(self, *argv, cwd=None): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + 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.probe), *argv], env=env, cwd=cwd, capture_output=True, text=True, + timeout=120) + for line in out.stdout.splitlines(): + if line.startswith("call\t"): + return line.split("\t")[1:] + if line.startswith("ret\t"): + return line.split("\t")[1:] + self.fail(out.stdout + out.stderr) + + def test_a_script_without_a_shebang_runs_through_sh(self): + plain = str(self.dirs / "open/plain") + self.assertEqual(["/bin/sh", plain, "a"], self.call("vp", plain, "a")) + + def test_path_search_runs_a_script_without_a_shebang_through_sh(self): + plain = str(self.dirs / "open/plain") + self.assertEqual(["/bin/sh", plain, "a"], self.call("vpe", str(self.dirs / "open"), "plain", "a")) + + def test_a_denied_entry_earlier_in_path_is_skipped(self): + path = f"{self.dirs / 'locked'}:{self.dirs / 'open'}" + call = self.call("vpe", path, "tool", "x") + self.assertTrue(call[-2].endswith("/opt/probe/open/tool"), call) + self.assertEqual("x", call[-1]) + + def test_only_denied_entries_report_permission_denied(self): + self.assertEqual(["-1", os.strerror(13)], self.call("vpe", str(self.dirs / "locked"), "tool")) + + def test_an_empty_path_entry_means_the_current_directory(self): + here = self.call("vpe", f"{self.dirs / 'open'}:", "here", cwd=self.root / "opt/probe/work") + self.assertEqual(["/bin/sh", "here"], here) + + def test_a_bare_name_is_not_run_from_the_current_directory_without_an_empty_entry(self): + missing = self.call("vpe", str(self.dirs / "open"), "here", cwd=self.root / "opt/probe/work") + self.assertEqual(["-1", os.strerror(2)], missing) + + +if __name__ == "__main__": + unittest.main()