diff --git a/app/src/main/cpp/ddexec/ddexec.c b/app/src/main/cpp/ddexec/ddexec.c index c7e4384ce3..b4a1db085d 100644 --- a/app/src/main/cpp/ddexec/ddexec.c +++ b/app/src/main/cpp/ddexec/ddexec.c @@ -21,6 +21,7 @@ #define SYS_munmap 215 #define SYS_mmap 222 #define SYS_mprotect 226 +#define SYS_getpid 172 #define AT_FDCWD_ (-100) #define O_RDONLY_ 0 @@ -52,6 +53,21 @@ static size_t slen(const char *s) { return n; } +static int seq(const char *a, const char *b) { + while (*a && *a == *b) a++, b++; + return *a == *b; +} + +static const char *env_get(char **envp, const char *name) { + size_t n = slen(name); + for (; *envp; envp++) { + size_t i = 0; + while (i < n && (*envp)[i] == name[i]) i++; + if (i == n && (*envp)[n] == '=') return *envp + n + 1; + } + return 0; +} + static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); } static void out_num(long v) { @@ -112,19 +128,43 @@ static int prot_of(uint32_t flags) { static void map_failed(const char *path, long r) { die("cannot map a segment", path, r); } -static void load(const char *path, struct image *im, uintptr_t page) { +static void read_interp(int fd, const Elf64_Phdr *ph, int phnum, char *interp, size_t size, const char *path) { + interp[0] = 0; + for (int i = 0; i < phnum; i++) { + if (ph[i].p_type != PT_INTERP) continue; + if (ph[i].p_filesz == 0 || ph[i].p_filesz >= size) die("bad PT_INTERP", path, 0); + if (xpread(fd, interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz) + die("truncated PT_INTERP", path, 0); + interp[ph[i].p_filesz] = 0; + } +} + +static int read_headers(const char *path, Elf64_Ehdr *eh, Elf64_Phdr *ph) { int fd = (int)sys6(SYS_openat, AT_FDCWD_, (long)path, O_RDONLY_ | O_CLOEXEC_, 0, 0, 0); if (fd < 0) die("cannot open", path, fd); - Elf64_Ehdr eh; - if (xpread(fd, &eh, sizeof(eh), 0) != (long)sizeof(eh)) die("not an ELF file", path, 0); - if (eh.e_ident[EI_MAG0] != ELFMAG0 || eh.e_ident[EI_MAG1] != ELFMAG1 || eh.e_ident[EI_MAG2] != ELFMAG2 || - eh.e_ident[EI_MAG3] != ELFMAG3 || eh.e_ident[EI_CLASS] != ELFCLASS64 || eh.e_machine != EM_AARCH64 || - (eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || eh.e_phentsize != sizeof(Elf64_Phdr) || - eh.e_phnum == 0 || eh.e_phnum > MAX_PHDRS) + if (xpread(fd, eh, sizeof(*eh), 0) != (long)sizeof(*eh)) die("not an ELF file", path, 0); + if (eh->e_ident[EI_MAG0] != ELFMAG0 || eh->e_ident[EI_MAG1] != ELFMAG1 || eh->e_ident[EI_MAG2] != ELFMAG2 || + eh->e_ident[EI_MAG3] != ELFMAG3 || eh->e_ident[EI_CLASS] != ELFCLASS64 || eh->e_machine != EM_AARCH64 || + (eh->e_type != ET_EXEC && eh->e_type != ET_DYN) || eh->e_phentsize != sizeof(Elf64_Phdr) || + eh->e_phnum == 0 || eh->e_phnum > MAX_PHDRS) die("not a 64-bit ARM ELF program", path, 0); + long size = (long)eh->e_phnum * (long)sizeof(Elf64_Phdr); + if (xpread(fd, ph, (size_t)size, (long)eh->e_phoff) != size) die("truncated program headers", path, 0); + return fd; +} + +static void interp_of(const char *path, char *interp, size_t size) { + Elf64_Ehdr eh; Elf64_Phdr ph[MAX_PHDRS]; - long size = (long)eh.e_phnum * (long)sizeof(Elf64_Phdr); - if (xpread(fd, ph, (size_t)size, (long)eh.e_phoff) != size) die("truncated program headers", path, 0); + int fd = read_headers(path, &eh, ph); + read_interp(fd, ph, eh.e_phnum, interp, size, path); + sys6(SYS_close, fd, 0, 0, 0, 0, 0); +} + +static void load(const char *path, struct image *im, uintptr_t page) { + Elf64_Ehdr eh; + Elf64_Phdr ph[MAX_PHDRS]; + int fd = read_headers(path, &eh, ph); uintptr_t lo = UINTPTR_MAX, hi = 0; for (int i = 0; i < eh.e_phnum; i++) { @@ -173,16 +213,9 @@ static void load(const char *path, struct image *im, uintptr_t page) { im->phnum = eh.e_phnum; im->phent = eh.e_phentsize; im->phdr = 0; - im->interp[0] = 0; - for (int i = 0; i < eh.e_phnum; i++) { + read_interp(fd, ph, eh.e_phnum, im->interp, sizeof(im->interp), path); + for (int i = 0; i < eh.e_phnum; i++) if (ph[i].p_type == PT_PHDR) im->phdr = bias + ph[i].p_vaddr; - if (ph[i].p_type == PT_INTERP) { - if (ph[i].p_filesz == 0 || ph[i].p_filesz >= sizeof(im->interp)) die("bad PT_INTERP", path, 0); - if (xpread(fd, im->interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz) - die("truncated PT_INTERP", path, 0); - im->interp[ph[i].p_filesz] = 0; - } - } if (!im->phdr) { for (int i = 0; i < eh.e_phnum; i++) { Elf64_Phdr *p = &ph[i]; @@ -202,6 +235,36 @@ static unsigned long auxv_get(const uintptr_t *auxv, unsigned long type, unsigne return fallback; } +static int is_self_exe(const char *execfn) { + if (!execfn) return 0; + if (seq(execfn, "/proc/self/exe") || seq(execfn, "/proc/thread-self/exe")) return 1; + const char *p = "/proc/"; + while (*p && *p == *execfn) p++, execfn++; + if (*p) return 0; + char num[24]; + int i = (int)sizeof(num) - 1; + num[i] = 0; + unsigned long pid = (unsigned long)sys6(SYS_getpid, 0, 0, 0, 0, 0, 0); + do { + num[--i] = (char)('0' + pid % 10); + pid /= 10; + } while (pid && i > 0); + const char *d = num + i; + while (*d && *d == *execfn) d++, execfn++; + return !*d && seq(execfn, "/exe"); +} + +static const char *guest_interp(char **envp, const char *interp, char *buf, size_t size) { + const char *root = env_get(envp, "DDNATV_ROOT"); + if (!root || interp[0] != '/') return interp; + size_t a = slen(root), b = slen(interp); + if (a + b + 1 > size) return interp; + for (size_t i = 0; i < a; i++) buf[i] = root[i]; + for (size_t i = 0; i <= b; i++) buf[a + i] = interp[i]; + if (sys6(SYS_faccessat, AT_FDCWD_, (long)buf, 0, 0, 0, 0) != 0) return interp; + return buf; +} + __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) { long argc = (long)sp[0]; char **argv = (char **)(sp + 1); @@ -211,25 +274,66 @@ __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) { uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1); long naux = 0; while (auxv[naux * 2] != AT_NULL) naux++; - if (argc < 3) die("usage: libddexec.so [args...]", 0, 0); + int reexec = is_self_exe((const char *)auxv_get(auxv, AT_EXECFN, 0)); + const char *path; + char **args = argv + 2; + long nargs = argc - 2; + char interp_buf[4096]; + char hook_buf[4096]; + if (reexec) { + path = env_get(envp, "DDNATV_REAL_EXE"); + if (!path || !path[0]) die("re-executed without DDNATV_REAL_EXE", 0, 0); + args = argv; + nargs = argc; + const char *lib_path = env_get(envp, "DDNATV_LIBRARY_PATH"); + char prog_interp[256]; + interp_of(path, prog_interp, sizeof(prog_interp)); + if (prog_interp[0] && lib_path && lib_path[0]) { + const char *ld_so = guest_interp(envp, prog_interp, interp_buf, sizeof(interp_buf)); + const char *hook = guest_interp(envp, "/usr/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf)); + if (hook != (const char *)hook_buf) hook = guest_interp(envp, "/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf)); + long n = argc > 1 ? argc - 1 : 0; + char **v = (char **)__builtin_alloca((size_t)(n + 9) * sizeof(char *)); + long k = 0; + v[k++] = (char *)ld_so; + if (hook == (const char *)hook_buf) { + v[k++] = (char *)"--preload"; + v[k++] = (char *)hook; + } + v[k++] = (char *)"--library-path"; + v[k++] = (char *)lib_path; + v[k++] = (char *)"--argv0"; + v[k++] = argc > 0 ? argv[0] : (char *)path; + v[k++] = (char *)path; + for (long i = 0; i < n; i++) v[k++] = argv[1 + i]; + v[k] = 0; + args = v; + nargs = k; + path = ld_so; + } + } else if (argc < 3) { + die("usage: libddexec.so [args...]", 0, 0); + } else { + path = argv[1]; + } uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096); - const char *path = argv[1]; struct image prog, interp; load(path, &prog, page); int has_interp = prog.interp[0] != 0; - if (has_interp) load(prog.interp, &interp, page); + if (has_interp) load(reexec ? guest_interp(envp, prog.interp, interp_buf, sizeof(interp_buf)) : prog.interp, &interp, page); // The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one. // The strings stay where the kernel put them. static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN}; long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0])); - long new_argc = argc - 2; + long new_argc = nargs; long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2; - uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15); + uintptr_t top = (uintptr_t)args < (uintptr_t)sp ? (uintptr_t)args : (uintptr_t)sp; + uintptr_t *nsp = (uintptr_t *)((top - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15); uintptr_t *w = nsp; *w++ = (uintptr_t)new_argc; - for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2]; + for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)args[i]; *w++ = 0; for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i]; *w++ = 0; diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index d4b99759d5..1a02e3420f 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -291,6 +291,18 @@ alone would then read as an installed client. spins until a `SIGALRM` handler sets a register (R12, or ESI in 32-bit `rt` and legacy frames): FEX-2611.1 with 0001 to 0011 never sees it in any of the three frame types, with this patch all three see it on the first signal, as natively. + - `0013-path-syscalls-through-libc`: FEX passes most path system calls of the guest (`mkdirat`, + `unlinkat`, `renameat`, `renameat2`, `symlinkat`, `linkat`, `mknodat`, `fchmodat`, `fchmodat2`, + `fchownat`, `utimensat`, `truncate`, `chdir`, `chroot`, `inotify_add_watch`) straight to the kernel + with an inline `svc`, which the native userland's path hook never sees, so an x86-64 program wrote + `/opt/...` or `/root/...` to the Android root instead of the rootfs, and `cd` into a rootfs folder + failed. They now go through libc's `syscall()`, which the hook maps like every other path; without + the hook it is the same system call. `tools/tests/test_native_hook_path_syscalls.py` checks the hook + side, including that an allocator which opens files before the hook has started does not hang. + FEX also mirrors each guest signal handler with `syscall(SYS_rt_sigaction, ...)`; for `SIGSYS` the + hook records the guest handler as it does for `sigaction()` and keeps its own installed, so a + program that sets a crash handler is no longer killed by the next blocked system call + (`tools/tests/test_native_hook_sigsys_mask.py`). - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, diff --git a/tools/fex/patches/0013-path-syscalls-through-libc.patch b/tools/fex/patches/0013-path-syscalls-through-libc.patch new file mode 100644 index 0000000000..122f7654d2 --- /dev/null +++ b/tools/fex/patches/0013-path-syscalls-through-libc.patch @@ -0,0 +1,130 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index 11ff163..085a621 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -209,6 +209,41 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, + } + #endif + ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough1(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1) { ++ uint64_t Result = ::syscall(syscall_num, arg1); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough2(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough3(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough4(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough5(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4, arg5); ++ SYSCALL_ERRNO(); ++} ++ + static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3); +@@ -238,9 +273,9 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(flock, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(fsync, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(fdatasync, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(truncate, SyscallPassthrough2); ++ REGISTER_SYSCALL_IMPL(truncate, SyscallPathPassthrough2); + REGISTER_SYSCALL_IMPL(getcwd, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(chdir, SyscallPassthrough1); ++ REGISTER_SYSCALL_IMPL(chdir, SyscallPathPassthrough1); + REGISTER_SYSCALL_IMPL(fchdir, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(fchmod, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(fchown, SyscallPassthrough3); +@@ -280,7 +315,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(mlock, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(munlock, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(pivot_root, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(chroot, SyscallPassthrough1); ++ REGISTER_SYSCALL_IMPL(chroot, SyscallPathPassthrough1); + REGISTER_SYSCALL_IMPL(sync, SyscallPassthrough0); + REGISTER_SYSCALL_IMPL(acct, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(mount, SyscallPassthrough5); +@@ -312,17 +347,17 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(keyctl, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL(ioprio_set, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(ioprio_get, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(inotify_rm_watch, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(migrate_pages, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(mkdirat, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(mknodat, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(fchownat, SyscallPassthrough5); +- REGISTER_SYSCALL_IMPL(unlinkat, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(renameat, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(linkat, SyscallPassthrough5); +- REGISTER_SYSCALL_IMPL(symlinkat, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(fchmodat, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(mkdirat, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(mknodat, SyscallPathPassthrough4); ++ REGISTER_SYSCALL_IMPL(fchownat, SyscallPathPassthrough5); ++ REGISTER_SYSCALL_IMPL(unlinkat, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(renameat, SyscallPathPassthrough4); ++ REGISTER_SYSCALL_IMPL(linkat, SyscallPathPassthrough5); ++ REGISTER_SYSCALL_IMPL(symlinkat, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(fchmodat, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(unshare, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(splice, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL(tee, SyscallPassthrough4); +@@ -343,7 +378,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(kcmp, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL(sched_setattr, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(sched_getattr, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(renameat2, SyscallPassthrough5); ++ REGISTER_SYSCALL_IMPL(renameat2, SyscallPathPassthrough5); + REGISTER_SYSCALL_IMPL(getrandom, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(memfd_create, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(membarrier, SyscallPassthrough2); +@@ -468,7 +503,7 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(get_robust_list, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(sync_file_range, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(vmsplice, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPathPassthrough4); + REGISTER_SYSCALL_IMPL_X64(fallocate, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(timerfd_settime, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(timerfd_gettime, SyscallPassthrough2); +@@ -492,7 +527,7 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(cachestat, UnimplementedSyscallSafe); + } + if (Handler->IsHostKernelVersionAtLeast(6, 6, 0)) { +- REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPathPassthrough4); + } else { + REGISTER_SYSCALL_IMPL_X64(fchmodat2, UnimplementedSyscallSafe); + } +@@ -529,7 +564,7 @@ namespace x32 { + REGISTER_SYSCALL_IMPL_X32(timer_settime64, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X32(timerfd_gettime64, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X32(timerfd_settime64, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPathPassthrough4); + REGISTER_SYSCALL_IMPL_X32(ppoll_time64, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL_X32(io_pgetevents_time64, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL_X32(mq_timedsend_time64, SyscallPassthrough5); diff --git a/tools/nativeguest/hook/env.c b/tools/nativeguest/hook/env.c index e881ba1f71..8f3daf8086 100644 --- a/tools/nativeguest/hook/env.c +++ b/tools/nativeguest/hook/env.c @@ -72,7 +72,7 @@ static char *map_preload_paths(const char *value) { return out; } -static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { +static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const char *lib_path) { init_ddnatv_hook(); int count = 0; int has_preload = 0; @@ -164,6 +164,9 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) { continue; } + if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) { + continue; + } new_env[dst++] = envp[i]; } @@ -178,6 +181,15 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { new_env[dst++] = str; } } + if (chosen_real_exe && lib_path && lib_path[0] != '\0') { + size_t len = strlen(lib_path); + char *str = malloc(20 + len + 1); + if (str) { + memcpy(str, "DDNATV_LIBRARY_PATH=", 20); + memcpy(str + 20, lib_path, len + 1); + new_env[dst++] = str; + } + } char hook_buf[PATH_MAX]; const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL; diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index 3f316fc3b3..664b0beedf 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -44,8 +44,8 @@ static void resolve_symlinks(const char *path, char *out, size_t out_size, int d resolve_symlinks(next_path, out, out_size, depth + 1); } -static char **ensure_hook_in_envp(char *const envp[], const char *real_exe) { - return prepare_ddnatv_env(envp, real_exe); +static char **ensure_hook_in_envp(char *const envp[], const char *real_exe, const char *lib_path) { + return prepare_ddnatv_env(envp, real_exe, lib_path); } // The file whose header decides how to start `target`: the symlink-resolved ELF (so ld.so and @@ -162,7 +162,7 @@ static int exec_interp_missing(int fd) { syscall(SYS_pread64, fd, interp, ph.p_filesz, (long)ph.p_offset) != (long)ph.p_filesz) return ENOEXEC; interp[ph.p_filesz] = 0; - int ifd = (int)syscall(SYS_openat, AT_FDCWD, interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK); + int ifd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); if (ifd < 0) return errno; syscall(SYS_close, ifd); return 0; @@ -174,7 +174,7 @@ static int exec_interp_missing(int fd) { // a shell walking $PATH moves on at ENOENT and EACCES, and runs a file without "#!" as a script at // ENOEXEC. static int exec_preflight(const char *path) { - int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC | O_NONBLOCK); + int fd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); if (fd < 0) return errno; struct stat st; int err = 0; @@ -428,7 +428,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ENOMEM; return -1; } - char **new_env = ensure_hook_in_envp(envp, elf_target); + char **new_env = ensure_hook_in_envp(envp, elf_target, ld_lib_path); int ret = run_execve(orig_execve, ld_so, new_argv, new_env); if (errno == EACCES && chmod(ld_so, 0755) == 0) { // ld.so without its exec bit (an unusual restore): fix it once and retry @@ -452,7 +452,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } if (new_argv) { prepare_static_program(static_elf); // ld.so is a static program itself - char **ddnatv_env = prepare_ddnatv_env(envp, target); + char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -486,7 +486,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ELOOP; ret = -1; } else { - char **ddnatv_env = prepare_ddnatv_env(envp, NULL); + char **ddnatv_env = prepare_ddnatv_env(envp, NULL, NULL); ret = ddnatv_execve(rewritten_interp, new_argv, ddnatv_env, depth + 1); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -506,7 +506,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } if (static_elf) prepare_static_program(static_elf); - char **ddnatv_env = prepare_ddnatv_env(envp, target); + char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); int ret = run_execve(orig_execve, target, argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -948,17 +948,21 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, // Android programs get Android's environment, as execve() gives them: the glibc hook in // LD_PRELOAD crashes them. - char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target) : clean_env_for_system(orig_ep); + int via_ld_so = has_ld_so && strcmp(elf_target, ld_so) != 0; + char ld_lib_path[PATH_MAX * 6]; + ld_lib_path[0] = '\0'; + if (via_ld_so) + build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path)); + char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target, via_ld_so ? ld_lib_path : NULL) + : clean_env_for_system(orig_ep); int ret = -1; - if (has_ld_so && strcmp(elf_target, ld_so) != 0) { + if (via_ld_so) { ensure_exec_bit(elf_target, probe.mode); if (probe.android_interp) prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42) char hook_buf[PATH_MAX]; const char *hook_so = ddnatv_hook_library(hook_buf, sizeof(hook_buf)); - char ld_lib_path[PATH_MAX * 6]; - build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path)); char **new_argv = build_ldso_argv(ld_so, hook_so, ld_lib_path, elf_target, prog_name, argv); if (!new_argv) { ret = ENOMEM; diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 7bf0a8b692..09a1074b86 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -519,6 +519,13 @@ static int close_range_all(unsigned int first, unsigned int last, int flags) { static __thread int t_syscall_redirect = 0; +static long nested_path_syscall(long number, unsigned long dirfd, unsigned long pathname, unsigned long arg3, unsigned long arg4) { + char nested_buf[PATH_MAX]; + const char *path = (const char *)pathname; + if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); + return call_orig_syscall(number, dirfd, (unsigned long)path, arg3, arg4, 0, 0); +} + long syscall(long number, ...) { va_list ap; va_start(ap, number); @@ -563,6 +570,38 @@ long syscall(long number, ...) { } #endif +#ifdef __NR_rt_sigprocmask + if (number == __NR_rt_sigprocmask && arg2 && (arg1 == SIG_BLOCK || arg1 == SIG_SETMASK) && arg4 == sizeof(uint64_t)) { + uint64_t mask; + memcpy(&mask, (const void *)arg2, sizeof(mask)); + mask &= ~(1ULL << (SIGSYS - 1)); + return call_orig_syscall(number, arg1, (unsigned long)&mask, arg3, arg4, 0, 0); + } +#endif + +#ifdef __NR_rt_sigaction + if (number == __NR_rt_sigaction && arg1 == SIGSYS && arg4 == sizeof(uint64_t)) { + struct { void *handler; unsigned long flags; void *restorer; uint64_t mask; } kact, kold; + struct sigaction act, old; + memset(&act, 0, sizeof(act)); + if (arg2) { + memcpy(&kact, (const void *)arg2, sizeof(kact)); + act.sa_sigaction = (void (*)(int, siginfo_t *, void *))kact.handler; + act.sa_flags = (int)kact.flags; + memcpy(&act.sa_mask, &kact.mask, sizeof(kact.mask)); + } + remember_app_sigsys(arg2 ? &act : NULL, arg3 ? &old : NULL); + if (arg3) { + memset(&kold, 0, sizeof(kold)); + kold.handler = (void *)old.sa_sigaction; + kold.flags = (unsigned long)(unsigned int)old.sa_flags; + memcpy(&kold.mask, &old.sa_mask, sizeof(kold.mask)); + memcpy((void *)arg3, &kold, sizeof(kold)); + } + return 0; + } +#endif + #ifdef __NR_seccomp if (number == __NR_seccomp) { return (long)seccomp((unsigned int)arg1, (unsigned int)arg2, (void *)arg3); @@ -618,16 +657,84 @@ long syscall(long number, ...) { } #endif + if (g_initialized) { +#ifdef __NR_openat + if (number == __NR_openat) { + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4); + t_syscall_redirect++; + long ret = (long)openat((int)arg1, (const char *)arg2, (int)arg3, (mode_t)arg4); + t_syscall_redirect--; + return ret; + } +#endif +#if defined(__NR_mkdirat) + if (number == __NR_mkdirat) { + return (long)mkdirat((int)arg1, (const char *)arg2, (mode_t)arg3); + } +#endif +#if defined(__NR_unlinkat) + if (number == __NR_unlinkat) { + return (long)unlinkat((int)arg1, (const char *)arg2, (int)arg3); + } +#endif +#if defined(__NR_renameat) + if (number == __NR_renameat) { + return (long)renameat((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4); + } +#endif +#if defined(__NR_renameat2) + if (number == __NR_renameat2) { + return (long)renameat2((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4, (unsigned int)arg5); + } +#endif +#if defined(__NR_symlinkat) + if (number == __NR_symlinkat) { + return (long)symlinkat((const char *)arg1, (int)arg2, (const char *)arg3); + } +#endif +#if defined(__NR_fchmodat) + if (number == __NR_fchmodat) { + return (long)fchmodat((int)arg1, (const char *)arg2, (mode_t)arg3, 0); + } +#endif +#if defined(__NR_fchownat) + if (number == __NR_fchownat) { + return (long)fchownat((int)arg1, (const char *)arg2, (uid_t)arg3, (gid_t)arg4, (int)arg5); + } +#endif +#if defined(__NR_utimensat) + if (number == __NR_utimensat) { + if (!arg2) return call_orig_syscall(number, arg1, arg2, arg3, arg4, 0, 0); + return (long)utimensat((int)arg1, (const char *)arg2, (const struct timespec *)arg3, (int)arg4); + } +#endif +#if defined(__NR_truncate) + if (number == __NR_truncate) { + return (long)truncate((const char *)arg1, (off_t)arg2); + } +#endif +#if defined(__NR_chdir) + if (number == __NR_chdir) { + return (long)chdir((const char *)arg1); + } +#endif +#if defined(__NR_chroot) + if (number == __NR_chroot) { + return (long)chroot((const char *)arg1); + } +#endif +#if defined(__NR_inotify_add_watch) + if (number == __NR_inotify_add_watch) { + return (long)inotify_add_watch((int)arg1, (const char *)arg2, (uint32_t)arg3); + } +#endif + } + #ifdef __NR_openat2 if (number == __NR_openat2) { // libddsession's openat2() calls syscall() again (an endless loop until the stack ran out): the nested // call maps the path and goes straight to the kernel - if (t_syscall_redirect) { - char nested_buf[PATH_MAX]; - const char *path = (const char *)arg2; - if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); - return call_orig_syscall(number, arg1, (unsigned long)path, arg3, arg4, 0, 0); - } + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4); t_syscall_redirect++; long ret = (long)openat2((int)arg1, (const char *)arg2, (struct ddnatv_open_how *)arg3, (size_t)arg4); t_syscall_redirect--; @@ -649,12 +756,7 @@ long syscall(long number, ...) { #if defined(__NR_faccessat) if (number == __NR_faccessat) { - if (t_syscall_redirect) { - char nested_buf[PATH_MAX]; - const char *path = (const char *)arg2; - if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); - return call_orig_syscall(number, arg1, (unsigned long)path, arg3, 0, 0, 0); - } + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, 0); t_syscall_redirect++; long ret = (long)faccessat((int)arg1, (const char *)arg2, (int)arg3, 0); t_syscall_redirect--; diff --git a/tools/tests/test_ddexec_reexec.py b/tools/tests/test_ddexec_reexec.py new file mode 100644 index 0000000000..640db1706c --- /dev/null +++ b/tools/tests/test_ddexec_reexec.py @@ -0,0 +1,154 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +REPO = Path(__file__).resolve().parents[2] +SOURCE = REPO / "app/src/main/cpp/ddexec/ddexec.c" +SYSROOT = Path("/usr/aarch64-linux-gnu") + +LIBRARY = r""" +int dd_probe_value(void) { return 7; } +""" + +HOOK = r""" +#include + +__attribute__((constructor)) static void hooked(void) { write(1, "hooked\n", 7); } +""" + +PROGRAM = r""" +#include +#include +#include +#include +#include + +int dd_probe_value(void); + +int main(int argc, char **argv, char **envp) { + if (dd_probe_value() != 7) return 4; + if (argc > 1 && strcmp(argv[1], "again") == 0) { + for (int i = 0; i < argc; i++) printf("%s%s", i ? "|" : "", argv[i]); + printf("\n%s\n", (char *)getauxval(AT_EXECFN)); + return 0; + } + char *next[] = {"first", "again", "x y", NULL}; + syscall(SYS_execveat, -100, "/proc/self/exe", next, envp, 0); + return 3; +} +""" + + +def ndk_clang(): + sdk = Path(os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") or Path.home() / "Android/Sdk") + for ndk in sorted((sdk / "ndk").glob("*"), reverse=True): + clang = ndk / "toolchains/llvm/prebuilt/linux-x86_64/bin/clang" + if clang.exists(): + return str(clang) + return shutil.which("clang") + + +class DdexecReexecTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cc, prefix = runner() + clang = ndk_clang() + if cc is None or clang is None or not shutil.which("bwrap") or not SYSROOT.is_dir(): + raise unittest.SkipTest("no aarch64 toolchain, runner or bwrap") + cls.qemu = list(prefix[:3]) if prefix else [] + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.loader = tmp / "libddexec.so" + subprocess.run([clang, "--target=aarch64-linux-android29", "-shared", "-fPIC", "-O2", "-ffreestanding", + "-fno-builtin", "-fno-stack-protector", "-fno-asynchronous-unwind-tables", "-nostdlib", + "-Wl,-e,_start", "-Wl,-z,noexecstack", "-Wl,--no-undefined", "-Wl,-Bsymbolic", + "-Wl,-z,max-page-size=16384", "-o", str(cls.loader), str(SOURCE)], check=True) + cls.libdir = tmp / "own-lib" + cls.libdir.mkdir() + (tmp / "lib.c").write_text(LIBRARY) + subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.libdir / "libddprobe.so"), str(tmp / "lib.c")], + check=True) + (tmp / "prog.c").write_text(PROGRAM) + cls.program = tmp / "prog" + subprocess.run([cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c"), "-L", str(cls.libdir), "-lddprobe"], + check=True) + cls.root = tmp / "root" + (cls.root / "usr/lib").mkdir(parents=True) + (cls.root / "lib").mkdir() + shutil.copy2(SYSROOT / "lib/ld-linux-aarch64.so.1", cls.root / "lib/ld-linux-aarch64.so.1") + (tmp / "hook.c").write_text(HOOK) + subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.root / "usr/lib/libddnatv-hook.so"), str(tmp / "hook.c")], + check=True) + probe = subprocess.run(["bwrap", "--dev-bind", "/", "/", "true"], capture_output=True) + if probe.returncode != 0: + raise unittest.SkipTest("bwrap cannot create a namespace here") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def env(self, real_exe, library_path=None, root=SYSROOT): + env = {k: v for k, v in os.environ.items() if not k.startswith(("DDNATV_", "LD_", "QEMU_"))} + env["DDNATV_ROOT"] = str(root) + env["LD_LIBRARY_PATH"] = f"{SYSROOT / 'lib'}:{self.libdir}" if library_path is None else str(SYSROOT / "lib") + if real_exe: + env["DDNATV_REAL_EXE"] = str(real_exe) + if library_path: + env["DDNATV_LIBRARY_PATH"] = library_path + return env + + def reexec(self, execfn, real_exe, library_path=None, root=SYSROOT): + jail = ["bwrap", "--dev-bind", "/", "/", "--tmpfs", "/proc"] + parent = str(Path(execfn).parent) + jail += ["--dir", parent, "--ro-bind", str(self.loader), execfn] + start = self.qemu + ["-0", "first", execfn] if self.qemu else ["bash", "-c", 'exec -a first "$0" "$@"', execfn] + cmd = jail + start + ["again", "x y"] + return subprocess.run(cmd, env=self.env(real_exe, library_path, root), capture_output=True, text=True, timeout=120) + + def test_reexec_through_proc_self_exe_runs_the_guest_program(self): + out = self.reexec("/proc/self/exe", self.program) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_through_thread_self_exe_runs_the_guest_program(self): + out = self.reexec("/proc/thread-self/exe", self.program) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_finds_libraries_through_the_recorded_library_path(self): + out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}") + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_through_ld_so_preloads_the_hook_of_the_root(self): + out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}", self.root) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["hooked", "first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_without_a_known_program_fails_cleanly(self): + out = self.reexec("/proc/self/exe", None) + self.assertEqual(127, out.returncode) + self.assertIn("DDNATV_REAL_EXE", out.stderr) + + def test_a_started_program_keeps_its_own_arguments(self): + ldso = SYSROOT / "lib/ld-linux-aarch64.so.1" + cmd = self.qemu + [str(self.loader), str(ldso), "ld.so", "--library-path", f"{SYSROOT / 'lib'}:{self.libdir}", + str(self.program), "again", "a"] + out = subprocess.run(cmd, env=self.env(self.program), capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual([f"{self.program}|again|a", str(self.program)], out.stdout.splitlines()) + + def test_the_usage_check_still_applies_outside_a_reexec(self): + out = subprocess.run(self.qemu + [str(self.loader), str(self.program)], env=self.env(self.program), + capture_output=True, text=True, timeout=120) + self.assertEqual(127, out.returncode) + self.assertIn("usage", out.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_path_syscalls.py b/tools/tests/test_fex_path_syscalls.py new file mode 100644 index 0000000000..203f2eaac1 --- /dev/null +++ b/tools/tests/test_fex_path_syscalls.py @@ -0,0 +1,49 @@ +import re +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0013-path-syscalls-through-libc.patch" +HOOK = REPO / "tools/nativeguest/hook/privileged.c" +PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp" +REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)\);") + + +def changed(): + removed, added = {}, {} + for line in PATCH.read_text().splitlines(): + found = REGISTER.search(line) + if found and line[:1] in "+-": + (added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:] + return removed, added + + +class FexPathSyscallsTest(unittest.TestCase): + def test_only_the_passthrough_table_changes(self): + self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH]) + + def test_each_path_syscall_keeps_its_arity_and_goes_through_libc(self): + removed, added = changed() + self.assertEqual(sorted(removed), sorted(added)) + self.assertGreater(len(added), 10) + for name, (template, arity, number) in added.items(): + with self.subTest(name=name): + self.assertEqual(("SyscallPassthrough", arity, number), removed[name]) + self.assertEqual("SyscallPathPassthrough", template) + + def test_the_new_templates_call_the_libc_syscall(self): + added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + calls = [line for line in added if "syscall(" in line and "Result" in line] + self.assertEqual(5, len(calls)) + self.assertTrue(all("::syscall(syscall_num" in line for line in calls)) + self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))]) + + def test_every_routed_syscall_is_rewritten_by_the_hook(self): + hook = HOOK.read_text() + for name, (_, _, number) in changed()[1].items(): + with self.subTest(name=name): + self.assertIn(f"number == __NR_{number})", hook) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_ldso_spawn.py b/tools/tests/test_native_hook_ldso_spawn.py index 48ed15b2fb..43b810344a 100644 --- a/tools/tests/test_native_hook_ldso_spawn.py +++ b/tools/tests/test_native_hook_ldso_spawn.py @@ -15,24 +15,27 @@ RECORDER = r""" #define _GNU_SOURCE #include #include +#include #include -static void show(const char *path, char *const argv[]) { +static void show(const char *path, char *const argv[], char *const envp[]) { printf("call\t%s", path); for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]); printf("\n"); + for (int i = 0; envp && envp[i]; i++) + if (strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) printf("libpath\t%s\n", envp[i] + 20); fflush(stdout); } int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions, const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { - show(path, argv); + show(path, argv, envp); if (pid) *pid = 1; return 0; } int execve(const char *path, char *const argv[], char *const envp[]) { - show(path, argv); + show(path, argv, envp); _exit(0); } """ @@ -114,6 +117,7 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): env.update(hook_env) out = subprocess.run(cmd + [str(self.probe), how, *argv], env=env, capture_output=True, text=True, timeout=120) calls = [line.split("\t")[1:] for line in out.stdout.splitlines() if line.startswith("call\t")] + self.library_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("libpath\t")] self.assertEqual(1, len(calls), out.stdout + out.stderr) if how == "spawn": self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr) @@ -142,6 +146,18 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self): self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x")) + def test_a_program_started_through_ldso_records_its_library_path(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + argv = self.call(how, GUEST_TOOL, "x")[1:] + self.assertEqual([argv[argv.index("--library-path") + 1]], self.library_paths) + + def test_ldso_started_by_name_records_no_library_path(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + self.call(how, GUEST_LDSO, "--list", GUEST_TOOL) + self.assertEqual([], self.library_paths) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/test_native_hook_path_syscalls.py b/tools/tests/test_native_hook_path_syscalls.py new file mode 100644 index 0000000000..ab69fc3c83 --- /dev/null +++ b/tools/tests/test_native_hook_path_syscalls.py @@ -0,0 +1,163 @@ +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" + +PROBE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +static void show(const char *name, long ret) { printf("%s\t%d\n", name, ret >= 0); } + +int main(int argc, char **argv) { + const char *dir = argv[1]; + char p[PATH_MAX], q[PATH_MAX], cwd[PATH_MAX]; + snprintf(p, sizeof(p), "%s/made", dir); + show("mkdirat", syscall(SYS_mkdirat, AT_FDCWD, p, 0755)); + snprintf(p, sizeof(p), "%s/made/file", dir); + long fd = syscall(SYS_openat, AT_FDCWD, p, O_WRONLY | O_CREAT | O_CLOEXEC, 0644); + show("openat", fd); + if (fd >= 0) close((int)fd); + show("truncate", syscall(SYS_truncate, p, 4)); + show("fchmodat", syscall(SYS_fchmodat, AT_FDCWD, p, 0600)); + show("utimensat", syscall(SYS_utimensat, AT_FDCWD, p, NULL, 0)); + fd = syscall(SYS_openat, AT_FDCWD, p, O_RDONLY | O_CLOEXEC); + show("futimens", fd >= 0 ? syscall(SYS_utimensat, (int)fd, NULL, NULL, 0) : -1); + if (fd >= 0) close((int)fd); + snprintf(q, sizeof(q), "%s/made/moved", dir); + show("renameat", syscall(SYS_renameat, AT_FDCWD, p, AT_FDCWD, q)); + show("renameat2", syscall(SYS_renameat2, AT_FDCWD, q, AT_FDCWD, p, 0)); + snprintf(q, sizeof(q), "%s/made/link", dir); + show("symlinkat", syscall(SYS_symlinkat, "file", AT_FDCWD, q)); + show("unlinkat", syscall(SYS_unlinkat, AT_FDCWD, q, 0)); + snprintf(q, sizeof(q), "%s/made", dir); + show("chdir", syscall(SYS_chdir, q)); + show("cwd", getcwd(cwd, sizeof(cwd)) && strstr(cwd, "/made") ? 0 : -1); + show("unlinkat-file", syscall(SYS_unlinkat, AT_FDCWD, p, 0)); + show("unlinkat-dir", syscall(SYS_unlinkat, AT_FDCWD, q, AT_REMOVEDIR)); + return 0; +} +""" + +ALLOCATOR = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +extern void *__libc_malloc(size_t); +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static int ready; + +void *malloc(size_t size) { + if (!ready) { + pthread_mutex_lock(&lock); + if (!ready) { + long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/stat", O_RDONLY | O_CLOEXEC); + if (fd >= 0) close((int)fd); + ready = 1; + } + pthread_mutex_unlock(&lock); + } + return __libc_malloc(size); +} + +int main(void) { + puts("ready"); + return 0; +} +""" + +EARLY = r""" +#include + +__attribute__((constructor)) static void early(void) { free(malloc(1)); } +""" + +CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat", + "chdir", "cwd", "unlinkat-file", "unlinkat-dir") + + +class NativeHookPathSyscallsTest(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() + 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 / "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.root / "opt").mkdir(parents=True) + (tmp / "allocator.c").write_text(ALLOCATOR) + cls.allocator = tmp / "allocator" + subprocess.run([cls.cc, "-O1", "-rdynamic", "-pthread", "-o", str(cls.allocator), str(tmp / "allocator.c")], check=True) + (tmp / "early.c").write_text(EARLY) + cls.early = tmp / "early.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.early), str(tmp / "early.c")], check=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_program(self, argv, hook_env): + 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) + return subprocess.run(cmd + argv, env=env, capture_output=True, text=True, timeout=120) + + def run_probe(self, guest_dir, hook=True): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {} + out = self.run_program([str(self.probe), guest_dir], hook_env) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: int(line.split("\t")[1]) for line in out.stdout.splitlines()} + + def test_guest_paths_through_syscall_land_in_the_root(self): + results = self.run_probe("/opt") + for call in CALLS: + with self.subTest(call=call): + self.assertEqual(1, results[call]) + self.assertEqual([], list((self.root / "opt").iterdir())) + + def test_paths_already_in_the_root_are_kept(self): + results = self.run_probe(str(self.root / "opt")) + for call in CALLS: + with self.subTest(call=call): + self.assertEqual(1, results[call]) + + def test_without_the_hook_guest_paths_reach_the_host(self): + results = self.run_probe("/opt/droiddeck-hook-probe-missing", hook=False) + self.assertEqual(0, results["mkdirat"]) + self.assertEqual(0, results["openat"]) + self.assertEqual(0, results["chdir"]) + + def test_an_allocator_opening_files_before_the_hook_starts_does_not_hang(self): + hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": "/proc:/proc", + "LD_PRELOAD": f"{self.hook}:{self.early}"} + out = self.run_program([str(self.allocator)], hook_env) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual("ready", out.stdout.strip()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_sigsys_mask.py b/tools/tests/test_native_hook_sigsys_mask.py new file mode 100644 index 0000000000..2d28c2954d --- /dev/null +++ b/tools/tests/test_native_hook_sigsys_mask.py @@ -0,0 +1,144 @@ +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" + +PROBE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static uint64_t current(void) { + uint64_t mask = 0; + syscall(SYS_rt_sigprocmask, SIG_SETMASK, NULL, &mask, sizeof(mask)); + return mask; +} + +struct kact { void *handler; unsigned long flags; void *restorer; uint64_t mask; }; + +static void own(int sig, siginfo_t *info, void *ctx) { (void)sig; (void)info; (void)ctx; } + +static long raw_sigaction(int sig, const struct kact *act, struct kact *old) { + register long x8 __asm__("x8") = SYS_rt_sigaction; + register long x0 __asm__("x0") = sig; + register long x1 __asm__("x1") = (long)act; + register long x2 __asm__("x2") = (long)old; + register long x3 __asm__("x3") = 8; + __asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory"); + return x0; +} + +static void handlers(void) { + struct kact act = { (void *)own, SA_SIGINFO, NULL, 0 }, seen, kernel; + syscall(SYS_rt_sigaction, SIGSYS, &act, NULL, 8); + syscall(SYS_rt_sigaction, SIGSYS, NULL, &seen, 8); + raw_sigaction(SIGSYS, NULL, &kernel); + printf("sigaction\t%d\t%d\n", seen.handler == (void *)own, kernel.handler == (void *)own); + struct kact usr1 = { (void *)own, SA_SIGINFO, NULL, 0 }; + syscall(SYS_rt_sigaction, SIGUSR1, &usr1, NULL, 8); + raw_sigaction(SIGUSR1, NULL, &kernel); + printf("sigaction-usr1\t%d\n", kernel.handler == (void *)own); +} + +static void show(const char *how) { + uint64_t mask = current(); + printf("%s\t%d\t%d\n", how, !!(mask & (1ULL << (SIGSYS - 1))), !!(mask & (1ULL << (SIGUSR1 - 1)))); + uint64_t none = 0; + syscall(SYS_rt_sigprocmask, SIG_SETMASK, &none, NULL, sizeof(none)); +} + +int main(int argc, char **argv) { + uint64_t all = ~0ULL; + sigset_t set; + sigfillset(&set); + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "syscall-setmask") == 0) syscall(SYS_rt_sigprocmask, SIG_SETMASK, &all, NULL, sizeof(all)); + else if (strcmp(argv[i], "syscall-block") == 0) syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all)); + else if (strcmp(argv[i], "syscall-unblock") == 0) { + syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all)); + uint64_t usr1 = 1ULL << (SIGUSR1 - 1); + syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &usr1, NULL, sizeof(usr1)); + } + else if (strcmp(argv[i], "sigprocmask") == 0) sigprocmask(SIG_SETMASK, &set, NULL); + else if (strcmp(argv[i], "pthread_sigmask") == 0) pthread_sigmask(SIG_SETMASK, &set, NULL); + else if (strcmp(argv[i], "sigaction") == 0) { + handlers(); + continue; + } + show(argv[i]); + } + return 0; +} +""" + +WAYS = ("syscall-setmask", "syscall-block", "sigprocmask", "pthread_sigmask") + + +class NativeHookSigsysMaskTest(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() + 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 / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + cls.root.mkdir() + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def masks(self, *ways, hook=True): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {} + 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), *ways], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: tuple(int(v) for v in line.split("\t")[1:]) for line in out.stdout.splitlines()} + + def test_blocking_every_signal_leaves_sigsys_open(self): + masks = self.masks(*WAYS) + for way in WAYS: + with self.subTest(way=way): + self.assertEqual((0, 1), masks[way]) + + def test_unblocking_is_unchanged(self): + self.assertEqual((0, 0), self.masks("syscall-unblock")["syscall-unblock"]) + + def test_a_sigsys_handler_set_through_syscall_keeps_the_hooks(self): + seen = self.masks("sigaction") + self.assertEqual((1, 0), seen["sigaction"]) + self.assertEqual((1,), seen["sigaction-usr1"]) + + def test_without_the_hook_a_sigsys_handler_reaches_the_kernel(self): + self.assertEqual((1, 1), self.masks("sigaction", hook=False)["sigaction"]) + + def test_without_the_hook_every_signal_is_blocked(self): + masks = self.masks(*WAYS, hook=False) + for way in WAYS: + with self.subTest(way=way): + self.assertEqual((1, 1), masks[way]) + + +if __name__ == "__main__": + unittest.main()