mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
fix(native): place a worker's fds after its exec so its binder threads cannot abort it
GuestWorker dup2()'d the guest's fds onto their numbers while the worker's binder threads were still running. A target that was the binder driver fd's number made the next binder ioctl fail with EACCES or ENOTTY, and libbinder aborts on that, so the worker died before its program ran. When it was the inner droiddeck-session, the session ended with status 0 two seconds after it started. Programs started through libddexec.so now get their fds placed by it after the exec (DDH_PLACE_FDS), when no other thread is left.
This commit is contained in:
1 parent
a6ffbe7d81
commit
49e70af1d0
6 files changed
+148
-4
No files matched your search
@@ -12,6 +12,7 @@
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define SYS_dup3 24
|
||||
#define SYS_faccessat 48
|
||||
#define SYS_openat 56
|
||||
#define SYS_close 57
|
||||
@@ -68,6 +69,14 @@ static const char *env_get(char **envp, const char *name) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const char PLACE_FDS[] = "DDH_PLACE_FDS";
|
||||
|
||||
static int is_place_fds(const char *entry) {
|
||||
size_t i = 0;
|
||||
while (PLACE_FDS[i] && entry[i] == PLACE_FDS[i]) i++;
|
||||
return !PLACE_FDS[i] && entry[i] == '=';
|
||||
}
|
||||
|
||||
static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); }
|
||||
|
||||
static void out_num(long v) {
|
||||
@@ -110,6 +119,46 @@ static long xpread(int fd, void *buf, size_t len, long off) {
|
||||
return (long)done;
|
||||
}
|
||||
|
||||
static const char *read_fd(const char *p, long *fd) {
|
||||
if (*p < '0' || *p > '9') return 0;
|
||||
long v = 0;
|
||||
while (*p >= '0' && *p <= '9' && v < (1L << 30)) v = v * 10 + (*p++ - '0');
|
||||
*fd = v;
|
||||
return p;
|
||||
}
|
||||
|
||||
static const char *read_pair(const char *p, long *from, long *to) {
|
||||
p = read_fd(p, from);
|
||||
if (!p || *p++ != ':') return 0;
|
||||
p = read_fd(p, to);
|
||||
if (!p || (*p && *p != ',')) return 0;
|
||||
return *p ? p + 1 : p;
|
||||
}
|
||||
|
||||
static int is_target(const char *spec, long fd) {
|
||||
long from, to;
|
||||
for (const char *p = spec; p && *p;) {
|
||||
p = read_pair(p, &from, &to);
|
||||
if (p && to == fd) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void place_fds(const char *spec) {
|
||||
long from, to;
|
||||
for (const char *p = spec; *p;) {
|
||||
p = read_pair(p, &from, &to);
|
||||
if (!p) die("bad DDH_PLACE_FDS", spec, 0);
|
||||
if (from == to) continue;
|
||||
long r = sys6(SYS_dup3, from, to, 0, 0, 0, 0);
|
||||
if (r < 0) die("cannot place an fd", spec, r);
|
||||
}
|
||||
for (const char *p = spec; *p;) {
|
||||
p = read_pair(p, &from, &to);
|
||||
if (!is_target(spec, from)) sys6(SYS_close, from, 0, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
struct image {
|
||||
uintptr_t base;
|
||||
uintptr_t phdr;
|
||||
@@ -274,6 +323,8 @@ __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++;
|
||||
const char *place = env_get(envp, PLACE_FDS);
|
||||
if (place) place_fds(place);
|
||||
int reexec = is_self_exe((const char *)auxv_get(auxv, AT_EXECFN, 0));
|
||||
const char *path;
|
||||
char **args = argv + 2;
|
||||
@@ -335,7 +386,8 @@ __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
|
||||
*w++ = (uintptr_t)new_argc;
|
||||
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];
|
||||
for (long i = 0; i < nenv; i++)
|
||||
if (!is_place_fds(envp[i])) *w++ = (uintptr_t)envp[i];
|
||||
*w++ = 0;
|
||||
for (long i = 0; i < naux; i++) {
|
||||
unsigned long type = auxv[i * 2];
|
||||
|
||||
@@ -96,12 +96,15 @@ open class GuestWorker : Service() {
|
||||
// Out of the way first, so that placing one fd cannot overwrite another not yet placed.
|
||||
val above = maxOf(MOVED_FDS, top + 1, binderTop + 1)
|
||||
val moved = fds.map { pfd -> pfd?.let { Os.fcntlInt(it.fileDescriptor, OsConstants.F_DUPFD, above) } }
|
||||
val deferred = argv.firstOrNull() == NativeGuest.execLoaderFile(this).path
|
||||
moved.forEachIndexed { i, fd ->
|
||||
if (fd == null || i >= targets.size) return@forEachIndexed
|
||||
val source = ParcelFileDescriptor.adoptFd(fd).also { kept.add(it) }.fileDescriptor
|
||||
if (deferred) return@forEachIndexed
|
||||
Os.dup2(source, targets[i])
|
||||
Os.fcntlInt(source, OsConstants.F_SETFD, OsConstants.FD_CLOEXEC)
|
||||
}
|
||||
val place = if (deferred) listOfNotNull(NativeGuest.placeFds(moved, targets)) else emptyList()
|
||||
// A session of its own: in zygote's process group, a program signalling its group
|
||||
// (kill(0, sig)) would reach every process of the app.
|
||||
runCatching { Os.setsid() }
|
||||
@@ -121,8 +124,8 @@ open class GuestWorker : Service() {
|
||||
// run ahead of the game. They get the asker's priority instead, as a forked child would.
|
||||
runCatching { Process.setThreadPriority(nice) }
|
||||
Os.execve(argv[0], argv.map(fill).toTypedArray(),
|
||||
env.filterNot { it.startsWith("DDH_WORKER_PID=") }.map(fill).toTypedArray() + mask +
|
||||
"DDH_WORKER_PID=${Process.myPid()}")
|
||||
env.filterNot { it.startsWith("DDH_WORKER_PID=") || it.startsWith("${NativeGuest.PLACE_FDS}=") }.map(fill)
|
||||
.toTypedArray() + mask + place + "DDH_WORKER_PID=${Process.myPid()}")
|
||||
} catch (e: ErrnoException) {
|
||||
Log.e(TAG, "could not exec ${argv.firstOrNull()}", e)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.nio.file.Files
|
||||
object NativeGuest {
|
||||
private const val TAG = "NativeGuest"
|
||||
const val HOOK = "usr/lib/libddnatv-hook.so"
|
||||
const val PLACE_FDS = "DDH_PLACE_FDS"
|
||||
private val LIB_DIRS = listOf("usr/lib", "usr/lib/aarch64-linux-gnu", "usr/local/lib", "usr/lib/systemd")
|
||||
|
||||
/** Libraries every native program loads before the hook, as /etc/ld.so.preload does for proot. */
|
||||
@@ -70,8 +71,14 @@ object NativeGuest {
|
||||
/** What starts the program at [path] from the host: nothing before it, or [execLoader] and the path. */
|
||||
fun execPrefix(path: String): List<String> = execLoader?.let { listOf(it, path) }.orEmpty()
|
||||
|
||||
fun execLoaderFile(context: Context): File = File(context.applicationInfo.nativeLibraryDir, "libddexec.so")
|
||||
|
||||
fun placeFds(fds: List<Int?>, targets: IntArray): String? =
|
||||
fds.withIndex().mapNotNull { (i, fd) -> if (fd == null || i >= targets.size) null else "$fd:${targets[i]}" }
|
||||
.takeIf { it.isNotEmpty() }?.joinToString(",", prefix = "$PLACE_FDS=")
|
||||
|
||||
fun init(context: Context) {
|
||||
execLoader = File(context.applicationInfo.nativeLibraryDir, "libddexec.so")
|
||||
execLoader = execLoaderFile(context)
|
||||
.takeIf { android.os.Build.VERSION.SDK_INT >= 29 && it.isFile }?.path
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,19 @@ class NativeGuestTest {
|
||||
File(it, "usr/lib/ld-linux-aarch64.so.1").writeText("")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aWorkerHandsLibddexecEveryFdWithItsNumber() {
|
||||
assertEquals("DDH_PLACE_FDS=1200:0,1201:1,1202:4,1203:801",
|
||||
NativeGuest.placeFds(listOf(1200, 1201, 1202, 1203), intArrayOf(0, 1, 4, 801)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aWorkerSkipsFdsItCouldNotMoveOrPlace() {
|
||||
assertEquals("DDH_PLACE_FDS=1200:0,1202:2", NativeGuest.placeFds(listOf(1200, null, 1202, 1203), intArrayOf(0, 1, 2)))
|
||||
assertEquals(null, NativeGuest.placeFds(listOf(null), intArrayOf(0)))
|
||||
assertEquals(null, NativeGuest.placeFds(emptyList(), intArrayOf()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRuntimeStillToBeInstalledRunsTheNextSessionNatively() {
|
||||
val empty = Files.createTempDirectory("native-root").toFile()
|
||||
|
||||
@@ -340,6 +340,14 @@ Things this needed, found the hard way:
|
||||
against `CLOSE_RANGE_CLOEXEC`); children never send it along with a handoff; and the hook closes
|
||||
copies in every other process (`DDH_WORKER_PID`), so a worker's exit is seen when its program
|
||||
exits. A worker that lost its binder fd was killed by Android within milliseconds.
|
||||
- **The program's fds are placed after the exec.** Until the exec, the worker's binder threads keep
|
||||
reading their driver fd, and libbinder aborts on any error there but `EBADF`
|
||||
(`IPCThreadState::joinThreadPool`: "getAndExecuteCommand(fd=4) returned unexpected error -13,
|
||||
aborting"). A `dup2()` of a guest fd onto that number (fd 4 on a Poco F7) killed the worker before
|
||||
its program ran, and a session whose inner `droiddeck-session` died that way ended with status 0
|
||||
two seconds after it started. The worker moves every fd above the binder fds and hands
|
||||
`libddexec.so` the list in `DDH_PLACE_FDS` (`source:target,...`); it places them before the
|
||||
program starts, when the exec has ended every other thread, and drops the variable.
|
||||
- **A session of its own (`setsid`) for every worker.** All app processes are in zygote's process
|
||||
group, so a program signalling its group reached the app itself (the hook also refuses
|
||||
`kill(0)`/`kill(-pgid)` into zygote's group, and `kill(-1)`). `reap_orphans` in the session
|
||||
|
||||
@@ -44,6 +44,34 @@ int main(int argc, char **argv, char **envp) {
|
||||
"""
|
||||
|
||||
|
||||
FD_PROBE = r"""
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static void show(int fd) {
|
||||
char buf[64];
|
||||
ssize_t n = read(fd, buf, sizeof(buf) - 1);
|
||||
if (n < 0) {
|
||||
printf("%d closed\n", fd);
|
||||
return;
|
||||
}
|
||||
buf[n] = 0;
|
||||
printf("%d %s cloexec=%d\n", fd, buf, fcntl(fd, F_GETFD) & FD_CLOEXEC);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
show(8);
|
||||
show(9);
|
||||
printf("1000 %s\n", fcntl(1000, F_GETFD) < 0 ? "closed" : "open");
|
||||
printf("1001 %s\n", fcntl(1001, F_GETFD) < 0 ? "closed" : "open");
|
||||
printf("env %s\n", getenv("DDH_PLACE_FDS") ? "kept" : "gone");
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
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):
|
||||
@@ -77,6 +105,11 @@ class DdexecReexecTest(unittest.TestCase):
|
||||
cls.program = tmp / "prog"
|
||||
subprocess.run([cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c"), "-L", str(cls.libdir), "-lddprobe"],
|
||||
check=True)
|
||||
(tmp / "fdprobe.c").write_text(FD_PROBE)
|
||||
cls.fd_probe = tmp / "fdprobe"
|
||||
subprocess.run([cc, "-O1", "-o", str(cls.fd_probe), str(tmp / "fdprobe.c")], check=True)
|
||||
(tmp / "first.txt").write_text("first")
|
||||
(tmp / "second.txt").write_text("second")
|
||||
cls.root = tmp / "root"
|
||||
(cls.root / "usr/lib").mkdir(parents=True)
|
||||
(cls.root / "lib").mkdir()
|
||||
@@ -143,6 +176,34 @@ class DdexecReexecTest(unittest.TestCase):
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
self.assertEqual([f"{self.program}|again|a", str(self.program)], out.stdout.splitlines())
|
||||
|
||||
def start_with_fds(self, place):
|
||||
tmp = Path(self.tmp.name)
|
||||
ldso = SYSROOT / "lib/ld-linux-aarch64.so.1"
|
||||
env = self.env(self.fd_probe)
|
||||
if place is not None:
|
||||
env["DDH_PLACE_FDS"] = place
|
||||
cmd = ["bash", "-c", 'exec 1000<"$0" 1001<"$1"; shift 2; exec "$@"', str(tmp / "first.txt"),
|
||||
str(tmp / "second.txt")] + self.qemu + [str(self.loader), str(ldso), "ld.so", "--library-path",
|
||||
str(SYSROOT / "lib"), str(self.fd_probe)]
|
||||
return subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=120)
|
||||
|
||||
def test_listed_fds_are_placed_at_their_numbers_before_the_program_starts(self):
|
||||
out = self.start_with_fds("1000:9,1001:8")
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
self.assertEqual(["8 second cloexec=0", "9 first cloexec=0", "1000 closed", "1001 closed", "env gone"],
|
||||
out.stdout.splitlines())
|
||||
|
||||
def test_a_start_without_placements_leaves_every_fd_where_it_is(self):
|
||||
out = self.start_with_fds(None)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
self.assertEqual(["8 closed", "9 closed", "1000 open", "1001 open", "env gone"], out.stdout.splitlines())
|
||||
|
||||
def test_a_malformed_placement_list_stops_before_the_program_runs(self):
|
||||
out = self.start_with_fds("1000:9,x")
|
||||
self.assertEqual(127, out.returncode)
|
||||
self.assertIn("bad DDH_PLACE_FDS", out.stderr)
|
||||
self.assertEqual("", out.stdout)
|
||||
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user