Skip to content

Latest commit

 

History

History
382 lines (286 loc) · 23.5 KB

important-notes.md

File metadata and controls

382 lines (286 loc) · 23.5 KB

Important Notes

See also:

  • docs/rust-toolchain-support.md — Rust toolchain support (vfork/CLONE_VM fix, link2symlink readlink fix)
  • docs/targetsdk35-compatibility.md — targetSdk 35 compatibility (SELinux W^X bypass, seccomp analysis)
  • docs/rust-port-pr-cli.md — Replace proot-distro.sh with Rust binary
  • docs/alpine-linux-support.md — Alpine Linux investigation and fixes
  • docs/integration-tests.md — Integration test suite (82 tests, 91 runs with the isolated readlink pass)
  • docs/proot-improvement.md — Our proot fork vs vendor/proot and vendor/termux-proot

Android W^X / SELinux / targetSdk Restrictions

Date: 2026-04-15 Device: Samsung, Android 16 (SDK 36), aarch64 () Context: Discovered during T5.2/T6.9 integration testing

What is W^X

Android enforces Write-XOR-Execute (W^X) policy on app processes. The kernel blocks execve() on files located in app-writable directories (labeled app_data_file by SELinux). This prevents apps from downloading and running arbitrary code.

The Three Blockers (targetSdk 29+)

When proot runs from the app process (u:r:untrusted_app:s0) with targetSdk >= 29:

proot error: execve("/bin/sh"): Permission denied            ← W^X blocks execve on app_data_file
proot error: can't chmod '/data/.../proot-XXXX': Function not implemented  ← seccomp ENOSYS
proot error: can't chdir to '/': Function not implemented     ← seccomp ENOSYS
  1. execve Permission denied: Proot's child tries to exec /bin/sh which resolves to the rootfs in /data/data/.... SELinux blocks it because the file has the app_data_file label.

  2. chmod ENOSYS: Proot's tracer code needs to chmod() a temp file. The Android zygote's seccomp filter returns ENOSYS (Function not implemented).

  3. chdir ENOSYS: Proot's tracer code needs to chdir() into the rootfs. Same seccomp filter blocks it.

Why run-as Works But App Doesn't

run-as id.or.oo.pr   → SELinux context: u:r:runas_app:s0:c3,c258,c512,c768  → proot works
app process          → SELinux context: u:r:untrusted_app:s0:c3,c258,c512,c768  → proot blocked

runas_app has different SELinux policies than untrusted_app. The W^X and seccomp restrictions only apply to untrusted_app.

targetSdk Threshold

Tested on device:

targetSdk proot login Notes
28 WORKS No W^X enforcement. Proot can execve, chmod, chdir freely.
29+ WORKS Uses PROOT_LOADER mechanism (Phase 7) to bypass W^X. Requires unbundled loader binary in nativeLibraryDir.

Conclusion: targetSdk 35 works via the PROOT_LOADER mechanism. The loader (libproot-loader.so) lives in nativeLibraryDir where SELinux allows execve, and proot uses it to exec guest binaries without hitting W^X.

nativeLibraryDir is the Exception

Files in the APK's native library directory can be executed even from untrusted_app:

/data/app/~~<random>/<package>-<random>/lib/arm64/  → SELinux allows execve()
/data/data/<package>/files/                          → SELinux denies execve()

This is why libproot.so, libproot-loader.so, libpr-cli.so can all be exec'd — they're in nativeLibraryDir. But the rootfs binaries in /data/data/.../installed-rootfs/ cannot.

Why Proot Bind Mounts Don't Help

Proot's --bind is virtual — it only translates paths in ptrace syscall interception. When the kernel actually performs the execve(), it sees the real filesystem path (in /data/data/...), not the virtual guest path. So binding libbusybox.so:/bin/sh doesn't help — the kernel still tries to exec the real rootfs file.

Why the Fork Matters

The forkPty() JNI function forks the app process. The child inherits untrusted_app SELinux context AND the zygote's seccomp filter. This is different from run-as which creates a new process in runas_app context.

Implications for Future Android Versions

  • Android 15+: Google may further restrict ptrace or native library execution
  • Samsung Knox: Some firmware mounts /data/data/<pkg>/files/ with noexec flag
  • Yama ptrace_scope: Must be 0 or 1 for proot to work (Samsung defaults to 1, which allows parent→child ptrace)

Potential Workarounds (Future Research)

  1. Static ELF Loader (libexecloader.so): A custom no_std Rust binary in nativeLibraryDir that maps target ELF into memory via mmap (not execve). Proot rewrites execve("/bin/sh") to execve("libexecloader.so", ["/bin/sh"]). Solves the execve blocker but NOT the chmod/chdir seccomp blockers.

  2. Guest dynamic linker as proxy: Copy ld-musl-aarch64.so.1 into nativeLibraryDir. Proot rewrites execve to go through the linker. Unlikely to work because the linker needs a full Linux ABI.

  3. targetSdk 35 with PROOT_LOADER: Current working solution. The unbundled loader binary in nativeLibraryDir handles execve for guest binaries. Play Store compatible.

Zygote Seccomp Filter (targetSdk 35, aarch64)

Even at targetSdk=35, the Android zygote installs a BPF seccomp filter on the app process (Seccomp: 2, Seccomp_filters: 1). This filter cannot be removed. proot never installs a seccomp filter of its own, so PROOT_NO_SECCOMP=1 only silences proot's hint about seccomp (cli.c).

Syscalls the filter traps and what proot does. "Allowed from" is the first Android release whose bionic filter lets the call through, read from bionic's release tags; the default action for everything else is SECCOMP_RET_TRAP. "Never" means no release allows it.

Syscall Number Allowed from What proot does
renameat2 276 Always (Android 8 whitelist, SYSCALLS.TXT from 11; handler believed unreachable) With flags 0: restart as renameat. With any flag: -ENOSYS (RENAME_NOREPLACE and RENAME_EXCHANGE cannot be carried over)
clone3 435 Android 14 QPR2 -ENOSYS; glibc falls back to clone, which every filter allows
openat2 437 Android 16 r3 Never reaches the SIGSYS handler: -ENOSYS at the enter stage (see below)
faccessat2 439 Android 16 r3 With flags 0: restart as faccessat. With any flag: -ENOSYS. When the filter allows it, proot translates it at the enter stage, with AT_SYMLINK_NOFOLLOW honoured
process_madvise 440 android-12.0.0_r1 (handler unreachable from then) Return 0 (advisory)
linkat 37 Always (allowed since at least Android 8; handler believed unreachable) Return -EPERM, as for a hard link the kernel refuses; link2symlink handles hard links before this point
setuid, setgid, setreuid, setregid, setfsuid, setfsgid 146, 144, 145, 143, 151, 152 Never (app blocklist) Return 0 (fake_id0 handles the semantics)
set_robust_list 99 Never Return -ENOSYS
rseq 293 Never Return -ENOSYS, not logged (glibc calls it at every process start)
getcwd 17 Believed never needed Read tracee->fs->cwd, write it to the tracee buffer, return the length
chdir 49 Believed never needed Translate the path, update tracee->fs->cwd, return 0
fchdir 50 Believed never needed Resolve the dirfd to a path, update the cwd, return 0
faccessat 48 Believed never needed Return 0 (noop)
fchmodat 53 Believed never needed Return 0 (noop)
openat, fstatat64 56, 79 Believed never needed default: case returns -ENOENT (not -ENOSYS)
any other default: case returns -ENOSYS and logs the number once per proot process (for example kcmp 272, pkey_alloc 289, kexec_load 104). Numbers above 440 are answered at the enter stage (ENOSYS, or passed through for epoll_pwait2, landlock_* and mseal), so they never reach the SIGSYS handler or the log

The handlers for getcwd, chdir, fchdir, faccessat and fchmodat, and the default: ENOENT for openat and fstatat64, are believed unreachable under the zygote filter (audit P21): the filter is believed not to trap these calls on any Android version. They stay for now, and nothing documented here depends on them. If one were reached, faccessat and fchmodat would report success for anything.

setxattrat, getxattrat, listxattrat, removexattrat and fchmodat2 are allowed from Android 16 r3 as well; proot does not translate their paths, so the enter-stage rule below answers -ENOSYS.

Enter-stage ENOSYS. On arm64 with the default ABI, translate_syscall_enter (syscall/enter.c, refused_at_entry) returns -ENOSYS for openat2 (437) and for every number above 440 except epoll_pwait2 (441), landlock_* (444-446) and mseal (462). The path syscalls among them cannot be translated, so letting them through would resolve a guest path on the host. The allowed set above 440 was taken from bionic tag android-16.0.0_r4 (the vendored bionic has no Android 17 tags), so a path-free syscall that a later filter allows gets ENOSYS until it is added. The call is voided and the status stored as its result, so the guest sees ENOSYS on every Android version, whether or not the filter traps the call; where the filter traps the voided call, tracee/event.c suppresses that SIGSYS. A 32-bit (aarch32) guest is not covered and passes openat2 untranslated; the app supports no 32-bit guests. translate_sysnum (syscall/sysnum.c) maps a number at or above the table length to PR_void.

adb run-as has no filter. An app process started under adb run-as shows Seccomp: 0, so no SIGSYS is raised there and these handlers never run. Check them from inside the app (Test in the container menu).

Note: original enosys_test incorrectly used 281 for process_madvise; 281 is execveat on arm64.

aarch64 x0 clobber bug: On aarch64, SYSARG_1 and SYSARG_RESULT both map to register x0. At SIGSYS time the kernel may clobber x0 before proot reads it. The handlers that read SYSARG_1 (chdir, fchdir, getcwd) use the ORIGINAL register version (saved right after fetch_regs()) instead of CURRENT; so do the renameat2 and faccessat2 handlers for their flags (SYSARG_5, SYSARG_4). The default: case reads the syscall number from CURRENT (for rseq). SYSARG_2-SYSARG_6 (x1-x5) are unaffected. Without this fix, fchdir(fd) appeared as fchdir(0) because x0 was clobbered to 0.

openat/fstatat64 ENOENT fix: The SIGSYS default: handler returns -ENOENT instead of -ENOSYS for these two syscalls. This is critical because musl's ldso path_open() treats ENOENT as "continue searching" but ENOSYS as "abort all search". Without this fix, a single failed openat on a non-existent path would prevent the dynamic linker from finding the real library.

Verified working (app process with seccomp: 2):

  • Alpine: apk update, apk add vim gcc rust cargo git openssh — all 0 errors
  • Debian: apt update && apt install vim gcc rustc cargo git openssh-client — all 0 errors
  • Full test suite (41 tests including ssh suite) on both Alpine and Debian

Key Files

  • android/app/build.gradle.kts — targetSdk = 35 (works via PROOT_LOADER mechanism)
  • src/proot/src/tracee/event.c — seccomp patch (skip proot's own seccomp filter)
  • src/proot/src/tracee/seccomp.c — SIGSYS handlers (16 handlers plus the rseq/set_robust_list/default: cases, x0 clobber fix, ENOENT for openat/fstatat64)
  • src/pr-cli/src/login.rs — proot invocation with PROOT_LOADER, PROOT_TMP_DIR, arg0("proot"), nativeLibraryDir paths
  • src/pr-cli/src/shared.rs — build_proot_args() with --change-id=0:0, --kernel-release, bind mounts
  • docs/alpine-linux-support.md — Alpine-specific investigation and seccomp findings
  • docs/proot-improvement.md — Full comparison of our proot vs vendor versions

Debian dpkg / apt Quirks on Android

apt-get install inside proot on Android hits two failures that do not occur on a native Linux system. Both stem from Android SELinux (untrusted_app domain) blocking filesystem operations that dpkg and package postinst scripts rely on.

See docs/proot-improvement.md §28 for the proot C-level fixes (lchown/utimensat ENOENT). This section covers the CLI-level workarounds in src/pr-cli/src/cmd_test.rs.

Failure 1 — dpkg unpack: lchown/utimensat ENOENT on .dpkg-new files

Symptom:

error setting ownership of /usr/bin/perlthanks.dpkg-new: No such file or directory
error setting timestamp of /usr/bin/perlthanks.dpkg-new: No such file or directory

Cause: link2symlink converts dpkg's link() calls into L2S symlink chains. proot's translated_path() dereferences those chains for lchown/utimensat, handing the kernel a deep app-data path. Android SELinux returns ENOENT (masqueraded EPERM) for such paths. dpkg aborts on ENOENT.

Fix: proot C changes in chown.c, fake_id0.c, link2symlink.c (see §28 in proot-improvement.md). No CLI workaround needed for this failure.


Failure 2 — openssh-client postinst: groupadd cannot lock /etc/group (fixed)

Symptom:

groupadd: /etc/group.23430 file stat error: No such file or directory
groupadd: cannot lock /etc/group; try again later.
fatal: `/sbin/groupadd -g 101 _ssh' returned error code 10. Exiting.

Cause: groupadd locks /etc/group by creating a hard link /etc/group.NNNNN. Android SELinux (untrusted_app) blocks link(), so link2symlink turns it into an L2S symlink chain whose content lives in PROOT_L2S_DIR. When that directory was the app cache dir, on a different filesystem from the rootfs, the chain could not be followed and groupadd exited 10.

Fix: every container now has its own <rootfs>/.l2s, created at install, and pr-cli sets PROOT_L2S_DIR to it (shared.rs). groupadd, groupadd --system and groupdel work in an Ubuntu container (checked 2026-11-07), and openssh-client's postinst creates _ssh itself.

Until 2026-11, pr-cli test worked around this by replacing groupadd/groupdel with no-op scripts and appending _ssh/_sshd to /etc/group by hand. The scripts stayed in the container after the test. A Debian or Ubuntu container that ran the test with an older pr-cli still has them; reinstalling the passwd package restores the real binaries: apt-get install --reinstall passwd.



pr-cli Caveats

Container /etc/environment and rootfs bind sources

A container's /etc/environment can no longer set PROOT_* variables: pr-cli login drops them, so proot gets only the PROOT_* settings from pr-cli and from the process that started it. The bind sources under the rootfs (tmp, proc/.*, sys/.empty) are bound only when they are the expected type (a real directory or regular file; any symlink is refused); otherwise pr-cli prints a warning on stderr and starts without that bind.

touch silently failed inside proot (fixed)

touch and Python's Path.touch() call utimensat on the path first and create the file only when it returns ENOENT. fake_id0's utimes EXIT handler forced every error to 0 (for dpkg on L2S symlinks; since 2026-11 only EPERM, EACCES and ENOENT), so touch /new/file exited 0 without creating the file. The handler now lets ENOENT through when the target does not exist on the host (docs/proot-improvement.md §28); the integration test "touch creates a missing file" covers it. Proot binaries built before this fix still need echo > /path/to/file.

Ubuntu 26.04 coreutils: unknown program 'libproot-loader' (fixed)

uutils coreutils 0.8 names its utility from AT_EXECFN as read through prctl(PR_GET_AUXV) / /proc/self/auxv, which held the loader's path. Proot now serves the loader-patched auxv from both (docs/proot-improvement.md §30). Older proot builds break every coreutils command and dpkg --configure on Ubuntu 26.04.

L2S links and the two app-data paths (fixed)

link2symlink stores absolute host paths. The app sees its data as /data/user/0/<pkg>; adb shell run-as starts pr-cli without APP_PREFIX, so it used /data/data/<pkg> and bound only that. proot resolves a symlink's absolute target as a guest path, so under run-as every L2S link made by the app (gcc, cc, ...) failed execve with ENOENT while stat still worked. build_proot_args() now also binds the other path of the app directory (app_dir_alias()).

The link2symlink store

The store, as it works now (link2symlink.c; pr-cli's install-time code in oci.rs (move_into_l2s, add_l2s_name, rename_noreplace) follows the same rule):

  • Layout: <rootfs>/.l2s holds, per hard-linked file, an intermediate symlink .l2s.<basename>NNNN that points to the data file .l2s.<basename>NNNN.CCCC. Every name of the file is a symlink to the intermediate; CCCC is the link count that stat reports.
  • Limits: groups 0001 to 9999 per basename, link count 0002 to 9999. Past either limit link() fails with EMLINK and the source stays a regular file.
  • Claiming a group: proot creates the intermediate as a symlink with symlink(), which is exclusive, then moves the data in with a no-replace renameat2. A taken intermediate or a stale data name (data without an intermediate) is skipped and the next group is tried; an existing file is never overwritten.
  • Adding a name: the data file is renamed to the next count (no-replace), then the intermediate is re-pointed atomically: a .new symlink is created beside it and renamed over it.
  • Rollback: if the destination symlink cannot be made (including a destination that already exists, EEXIST), the count is lowered again or, for a first link, the data moves back to the source name and the intermediate is removed.
  • Lowering counts: only at the exit stage of a rename or unlink, after it succeeded and the name is gone or now a different file (compared by device and inode). The name is remembered at syscall entry in per-tracee state. RENAME_EXCHANGE is excluded. A failed RENAME_NOREPLACE or a rename of a name onto itself keeps the count; the last name removed deletes the intermediate and the data.
  • Hard-linking a symlink that is not a store entry copies the symlink (same target); nothing enters the store.
  • A file that has been hard-linked stays a store entry after its other names are removed (its count drops to 1); this matches earlier behaviour.
  • Errors are returned as the real errno. EXDEV and others used to be reported as EPERM.

Known limits:

  • A user symlink whose target ends like a store name (.l2s.<x>) is treated as a store entry.
  • Renaming and unlinking one name at the same time in two sessions can lower its count twice.
  • A crash between steps can leave a .new temporary (removed at the next re-point of that intermediate) or a count one too high (the data is kept, never lost).
  • Stores whose counts are already wrong from older builds are not repaired.

Container DNS follows the active network

pr-cli used to write 8.8.8.8 / 8.8.4.4 (install) or 8.8.8.8 / 1.1.1.1 (login) into /etc/resolv.conf, and musl/glibc query those directly, so networks that drop direct public DNS broke apk/apt inside containers while Android itself still resolved. The app now passes the active network's DNS servers as APP_DNS_SERVERS; pr-cli writes up to two of them first, then the public servers as fallback (three nameservers at most), and refreshes the file at each login. A resolv.conf without pr-cli's marker line (and not an old pr-cli default) is left alone. IPv6 servers are passed only when the network has an IPv6 default route; otherwise (seen: IPv6-only DNS on mobile data) glibc would wait out its timeout on them before every lookup. The file is replaced atomically (temporary file + rename), and one that cannot be read as text is left alone.

Login user: home only, always fake root and /bin/sh

Current behaviour (src/pr-cli/src/login.rs, shared.rs):

  • pr-cli login <distro> --user <name> looks the user up in the container's /etc/passwd and fails if the user is missing, but only the home directory is used, as HOME. The session always starts in / (--cwd=/ in build_proot_args()).
  • The session always starts /bin/sh -l; the user's login shell from /etc/passwd is ignored (Ubuntu's /bin/bash for root, for example).
  • PRoot always gets --change-id=0:0, so every user, --user alice included, runs as fake root: id -u is 0 and new files appear owned by root.

History: 2f2bdbc started the passwd shell in the passwd home with --change-id=<uid>:<gid>; 96c383d (making login work under targetSdk 28 / W^X) replaced that with /bin/sh -l, --cwd=/ and --change-id=0:0 without recording why. AGENTS.md Critical Constraint 7 now requires --change-id=0:0: dpkg and other tools check getuid() == 0.

What could change, and what stands in the way:

  • Start in the home directory: pass the passwd home as --cwd. Low risk.
  • Login shell: try the passwd shell and fall back to /bin/sh -l. The check has to run inside the session (for example /bin/sh -l -c 'exec "$shell" -l || exec /bin/sh -l'), not on the host: shells are often absolute symlinks (/bin/sh -> /bin/busybox) or L2S links that point outside the rootfs when followed from the host, and under W^X the mode bits do not say whether a file can be executed.
  • Non-root users: not a matter of passing --change-id=<uid>:<gid>. It conflicts with Constraint 7, and fake_id0 is built around fake root:
    • every file owned by the real app uid, which is the whole rootfs, would appear owned by the user, and the kernel lets the app uid write all of it, so the user could edit /etc/passwd: there is no permission separation to gain;
    • chown() is answered with the caller's uid (chown.c), which non-root callers read as an error, and the utimes / permission-error masking applies only when euid == 0. It would need fake_id0 to keep its own per-file ownership, not just a flag.
  • Groups: this build is not USERLAND, so getgroups() returns the app's real Android gids (inet 3003 and others), which are not in /etc/group; id shows them.

Each of these changes what existing scripts see (id, $SHELL, $PWD), so it needs its own tests and a device run.

Commands and environment of pr-cli login

pr-cli login <distro> -- <args> runs /bin/sh -l in the guest:

  • with one argument, as a shell command: /bin/sh -l -c "<arg>". hr's gateway command and rs's scripts rely on this: pr-cli login alpine -- "apk update && apk add rust";
  • with two or more, as a program and its arguments: each is single-quoted (a ' becomes '\'') and the words are joined, so -- touch "a b" makes one file and $HOME;x stays literal. -- /bin/sh -c "apk update && apk add rust" now works too.

Until 2026-11 the arguments were joined with spaces into one -c string, which split arguments with spaces and let $, ; and quotes inside them act as shell syntax.

The guest starts from a clean environment: PATH, HOME, USER, TERM, COLORTERM, LANG, TMPDIR, the Android variables pr-cli has (ANDROID_ROOT, BOOTCLASSPATH and others), the container's /etc/environment (a value loses one pair of matching quotes, export and comments are skipped, keys must be shell names), and proot's own PROOT_* settings, which proot reads from its environment. Variables of the app or of whoever ran pr-cli (APP_PREFIX, the app's HOME) no longer reach the guest.


Project Name: pr

pr stands for PRoot — which is short for ptrace-based root.

PRoot is a user-space implementation of chroot, mount --bind, and binfmt_misc that uses Linux's ptrace() system call to intercept and translate filesystem paths. This allows running Linux distributions inside a directory without actual root privileges — exactly what this app does on Android.

The app package id.or.oo.pr inherits the name: a standalone Android APK that runs Linux distros via proot, with no Termux dependency.