Droidspaces-OSS icon indicating copy to clipboard operation
Droidspaces-OSS copied to clipboard

[FEATURE] Allocate container console PTY from container's private devpts instance to prevent host /dev/pts leakage`

Open ha7v opened this issue 1 month ago • 2 comments

Problem Description

Currently, when Droidspaces initializes a container console (e.g., in src/daemon.c / src/terminal.c), the PTY pair is allocated from the host's mount namespace by opening /dev/ptmx on the host side before or during container startup.

On Android, this causes two noticeable issues:

  1. Host /dev/pts Pollution & Detection Leakage: A slave PTY node (e.g., /dev/pts/2) is created under the host's /dev/pts directory with uid=0 (root) and SELinux context u:object_r:devpts:s0. On Android, normal apps (untrusted_app, UID >= 10000) own their respective PTYs, and ADB shell sessions belong to AID_SHELL (2000). A persistent uid=0 PTY slave on the host's /dev/pts never occurs naturally on stock Android and immediately exposes the presence of a running root daemon/container to runtime environment detectors (flagged as Abnormal Permission: Found ROOT PTY).
  2. Namespace Isolation & Security: Sharing the host's devpts instance with the container violates standard Linux container isolation practices and historically exposes containers to terminal injection boundary issues (e.g., TIOCSTI concerns if FDs are ever inherited across contexts).

Proposed Solution (Container-Private devpts)

Following industry-standard container runtimes (runc, LXC, systemd-nspawn), the console PTY should be allocated strictly from the container's own isolated devpts instance:

1. Mount a private devpts instance inside the container's Mount Namespace

Inside the container child process (after CLONE_NEWNS), mount a dedicated devpts with newinstance and bind-mount/symlink /dev/pts/ptmx to /dev/ptmx:

// 1. Mount isolated devpts instance (gid=5 is standard 'tty' group)
mount("devpts", "/dev/pts", "devpts", MS_NOSUID | MS_NOEXEC, "newinstance,ptmxmode=0666,mode=0620,gid=5");

// 2. Ensure /dev/ptmx points to the isolated instance for in-container apps (sshd, tmux, etc.)
mount("/dev/pts/ptmx", "/dev/ptmx", NULL, MS_BIND, NULL); 
// Or symlink("/dev/pts/ptmx", "/dev/ptmx") after unlinking the old node

2. Allocate the PTY from the private instance & obtain master_fd on the host

Note: To guarantee the kernel allocates from the new instance, we must open the ptmx node belonging to that specific devpts mount (/dev/pts/ptmx).

There are three clean ways for the host daemon (droidspacesd) to obtain the master_fd while keeping the slave node (/dev/pts/0) strictly inside the container:

  • Approach A (Simplest code change - Direct /proc path traversal): Once the child process finishes mounting its private /dev/pts (synchronized via a pipe/eventfd), the host daemon can directly open the child's private ptmx from the host side:

    snprintf(ptmx_path, sizeof(ptmx_path), "/proc/%d/root/dev/pts/ptmx", child_pid);
    int host_master_fd = open(ptmx_path, O_RDWR | O_NOCTTY | O_CLOEXEC);
    

    Why this works: Opening /dev/pts/ptmx through /proc/<pid>/root resolves the dentry inside the container's mount namespace. The slave node /dev/pts/0 is created exclusively inside the container, while the host daemon immediately gets the master_fd without needing IPC FD-passing!

  • Approach B (Industry Standard - socketpair + SCM_RIGHTS): The container child opens /dev/pts/ptmx locally, sets up /dev/pts/0 as its controlling terminal (setsid() + TIOCSCTTY), and sends the master_fd back to the host daemon over a pre-established AF_UNIX socketpair() using SCM_RIGHTS. (100% kernel version compatibility).

  • Approach C (Modern Syscall - pidfd_getfd on Kernel 5.6+): The child opens /dev/pts/ptmx, and the host daemon duplicates the descriptor using pidfd_open() + pidfd_getfd().


Benefits

  • Zero Host Pollution: The host's /dev/pts remains 100% clean and untainted—no root-owned slave nodes are ever created on the host.
  • Native Stealth: Completely eliminates Found ROOT PTY detections at the architectural root cause, without needing kernel-level LKM hooks or VFS getattr spoofing.
  • Standards Compliance: Aligns Droidspaces with the official Linux kernel devpts multi-instance container specification.

ha7v avatar Oct 22 '26 09:10 ha7v

thanks for the detailed writeup. you're right that there was a root-owned pty on the host, but the two halves you proposed were already in the tree:

  • the private devpts (newinstance, ptmxmode=0666, mode=0620, gid=5, pts/ptmx bound over /dev/ptmx) is what setup_devpts() in src/mount.c has done for a long time
  • enter and run already allocate their pty after setns and pass the master back over a socketpair with SCM_RIGHTS, which is your approach B

the actual leak was the boot console. start opened the console pty on the host before forking the monitor and bind-mounted that host /dev/pts/N over the container's /dev/console before pivot_root, so every running container pinned a root-owned slave in the host devpts for its whole life. that's the old pre-4.0 LXC model.

fixed in 3b6759c6 on dev. init now allocates the console itself from the devpts it just mounted, binds it over /dev/console by fd and hands the master+slave pair up to the monitor over a socketpair, the way LXC 4+ does it. foreground start, internal reboots and hw_access mode all still work, tested on a 5.15 phone. an idle container now leaves nothing in the host's /dev/pts.

two things worth knowing:

  • the daemon's session pty (the one behind the app terminal) still lives on the host for as long as a terminal tab is open. moving it into the guest devpts wouldn't change anything observable, because on a rooted phone every interactive root shell also comes with the su daemon's own root pty (magisk and ksu both allocate one), and that's outside droidspaces. so with a terminal open a detector will still see a root pty, with it closed it won't.
  • the TIOCSTI angle wasn't an escape in practice. the only readers of that slave were guest init and the monitor's master side, so injecting into it only fed the guest's own input queue. the fix is isolation hygiene more than a privilege boundary.

will be in the next release.

ravindu644 avatar Oct 23 '26 19:10 ravindu644

Hi @ravindu644, thanks for fixing the persistent boot-console PTY leak in 3b6759c6!

Wanted to share a quick follow-up finding regarding the daemon session PTY in src/daemon/session.c:54:

In your previous comment, you noted that moving the daemon session PTY wouldn't change what detectors see because su allocates its own uid=0 PTY. On Magisk (pts_proxy) that is true, however on KernelSU (and forks like FinaSU), su does NOT allocate a new root PTY — ksud (userspace/ksud/src/su.rs) elevates in-process and reuses/wraps the caller's existing non-root PTY (u0_aXXX from the Droidspaces app TerminalSession or shell from ADB).

We verified this on Android 17 (OnePlus 13T, kernel 6.6.144-4k, KernelSU / FinaSU):

  • su -c "ls -laZ /dev/pts/" shows only shell:shell (uid=2000) or u0_aXXX (untrusted_app_all_devpts), with no uid=0 PTY.
  • When opening the Droidspaces app's built-in terminal (which calls su -c 'droidspaces -n <name> enter root'), handle_session() in src/daemon/session.c:54 calls ds_openpty("/dev/ptmx", ...) as uid=0, making droidspacesd the sole source of a uid=0 PTY on host /dev/pts/ while a terminal tab is open.

Minimal Self-Contained Fix (Zero Host Namespace Changes)

On Linux 5.2+ kernels supporting the new mount API (fsopen / fsconfig / fsmount + TIOCGPTPEER), ds_openpty_private() can allocate the intermediate master/slave pair from a detached, unattached anonymous devpts (newinstance) mount fd, close the mount fd immediately, and fall back to /dev/ptmx on older kernels (< 5.2):

--- a/src/daemon/session.c
+++ b/src/daemon/session.c
@@ -51,7 +51,7 @@ void handle_session(int conn, ds_req_t *r) {
   char buf[DS_IOBUF];
 
   if (is_pty) {
-    if (ds_openpty("/dev/ptmx", &master, &slave, NULL) < 0) {
+    if (ds_openpty_private(&master, &slave) < 0) {
       ds_send_frame(conn, MSG_ERR, "daemon: openpty failed\n", 23);
       send_exit(conn, 1);
       return;
--- a/src/include/tty/tty.h
+++ b/src/include/tty/tty.h
@@ -19,6 +19,7 @@ int ds_terminal_proxy(int master_fd);
 
 /* pty.c */
 int ds_openpty(const char *ptmx, int *master, int *slave, char *name);
+int ds_openpty_private(int *master, int *slave);
 int ds_terminal_create(struct ds_tty_info *tty);
 int ds_terminal_set_stdfds(int fd);
 int ds_terminal_make_controlling(int fd);
--- a/src/tty/pty.c
+++ b/src/tty/pty.c
@@ -55,6 +55,83 @@ err:
   return -1;
 }
 
+#ifndef __NR_fsopen
+#define __NR_fsopen 430
+#endif
+#ifndef __NR_fsconfig
+#define __NR_fsconfig 431
+#endif
+#ifndef __NR_fsmount
+#define __NR_fsmount 432
+#endif
+#ifndef FSOPEN_CLOEXEC
+#define FSOPEN_CLOEXEC 0x00000001
+#endif
+#ifndef FSMOUNT_CLOEXEC
+#define FSMOUNT_CLOEXEC 0x00000001
+#endif
+#ifndef FSCONFIG_SET_FLAG
+#define FSCONFIG_SET_FLAG 0
+#endif
+#ifndef FSCONFIG_SET_STRING
+#define FSCONFIG_SET_STRING 1
+#endif
+#ifndef FSCONFIG_CMD_CREATE
+#define FSCONFIG_CMD_CREATE 6
+#endif
+#ifndef MOUNT_ATTR_NOSUID
+#define MOUNT_ATTR_NOSUID 0x00000002
+#endif
+#ifndef MOUNT_ATTR_NOEXEC
+#define MOUNT_ATTR_NOEXEC 0x00000008
+#endif
+
+/* Allocate master + slave from a detached anonymous devpts superblock via the
+ * Linux 5.2+ mount API (fsopen/fsconfig/fsmount + TIOCGPTPEER).  Because the
+ * mount descriptor is closed immediately after opening ptmx and never attached
+ * to any directory, neither host /dev/pts nor /proc/self/mountinfo sees the
+ * intermediate root-owned PTY.  Falls back to /dev/ptmx on older kernels. */
+int ds_openpty_private(int *master, int *slave) {
+  int fsfd = (int)syscall(__NR_fsopen, "devpts", FSOPEN_CLOEXEC);
+  if (fsfd < 0)
+    return ds_openpty("/dev/ptmx", master, slave, NULL);
+
+  if (syscall(__NR_fsconfig, fsfd, FSCONFIG_SET_FLAG, "newinstance", NULL, 0) <
+          0 ||
+      syscall(__NR_fsconfig, fsfd, FSCONFIG_SET_STRING, "ptmxmode", "0666", 0) <
+          0 ||
+      syscall(__NR_fsconfig, fsfd, FSCONFIG_SET_STRING, "mode", "0620", 0) <
+          0 ||
+      syscall(__NR_fsconfig, fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0) < 0) {
+    close(fsfd);
+    return ds_openpty("/dev/ptmx", master, slave, NULL);
+  }
+
+  int mntfd = (int)syscall(__NR_fsmount, fsfd, FSMOUNT_CLOEXEC,
+                           MOUNT_ATTR_NOSUID | MOUNT_ATTR_NOEXEC);
+  close(fsfd);
+  if (mntfd < 0)
+    return ds_openpty("/dev/ptmx", master, slave, NULL);
+
+  int m = openat(mntfd, "ptmx", O_RDWR | O_NOCTTY | O_CLOEXEC);
+  close(mntfd);
+  if (m < 0)
+    return ds_openpty("/dev/ptmx", master, slave, NULL);
+
+  int unlock = 0;
+  (void)ioctl(m, TIOCSPTLCK, &unlock);
+
+  int s = ioctl(m, TIOCGPTPEER, O_RDWR | O_NOCTTY | O_CLOEXEC);
+  if (s < 0) {
+    close(m);
+    return ds_openpty("/dev/ptmx", master, slave, NULL);
+  }
+
+  *master = m;
+  *slave = s;
+  return 0;
+}
+
 int ds_terminal_create(struct ds_tty_info *tty) {
   if (ds_openpty("/dev/ptmx", &tty->master, &tty->slave, tty->name) < 0) {
     ds_error("openpty failed: %s", strerror(errno));

Why this approach is clean:

  • Does not unshare(CLONE_NEWNS) inside the daemon worker (so foreground start mount propagation in handle_session() is completely untouched).
  • Adds zero entries to host /proc/self/mountinfo and zero nodes to host /dev/pts/.
  • Linux syscall numbers 430/431/432 are identical across all supported Droidspaces architectures (aarch64, x86_64, armhf, x86, riscv64), with automatic fallback to ds_openpty("/dev/ptmx", ...) if fsopen/fsmount/TIOCGPTPEER isn't available.

Live Test Result: Tested on OnePlus 13T (Android 17, kernel 6.6.144-4k, KernelSU/FinaSU) with a Debian 13 container running and the Droidspaces app's built-in interactive terminal open (tty inside container = /dev/pts/1, shell works normally):

  • Host /dev/pts/ only shows the unprivileged app node (u0_a648, untrusted_app_all_devpts) and ptmx — zero uid=0 entries.
  • Host /proc/mounts remains unchanged.
  • devpts permission probes report Clean.

Hope this helps! Happy to open a PR if you'd like this upstream.

yankedi avatar Nov 29 '26 08:11 yankedi