From 4eb388a9d7977138ad635204e6358ff6d51976fe Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Fri, 27 Nov 2026 07:05:37 +0300 Subject: [PATCH] Clone exact original meter directory across Docker mount namespace --- .github/workflows/ci.yml | 1 + docs/QUOTA_V2_GENESIS_QUARANTINE_HANDOFF.md | 29 ++++ .../public_tls_namespace_route.py | 3 +- .../public_tls_route_mount.py | 149 +++++++++++++++++- .../test_quota_v2_public_tls_foreign_mount.py | 126 +++++++++++++++ 5 files changed, 302 insertions(+), 6 deletions(-) create mode 100644 tests/test_quota_v2_public_tls_foreign_mount.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 96239395..6c62989c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -125,6 +125,7 @@ jobs: run: | python3 -m py_compile experiments/quota-v2-physical-stop/public_tls_route_mount.py experiments/quota-v2-physical-stop/public_tls_routes.py experiments/quota-v2-physical-stop/public_tls_namespace_route.py tests/test_quota_v2_public_tls_routes.py sudo env PATH="$PATH" python3 tests/test_quota_v2_public_tls_routes.py -v + sudo env PATH="$PATH" python3 -B tests/test_quota_v2_public_tls_foreign_mount.py -v - name: Actual capless private PID namespace proves original Unix meter by pidfs identity run: | python3 -m py_compile experiments/quota-v2-physical-stop/public_tls_peer_identity.py tests/test_quota_v2_public_tls_peer_identity.py diff --git a/docs/QUOTA_V2_GENESIS_QUARANTINE_HANDOFF.md b/docs/QUOTA_V2_GENESIS_QUARANTINE_HANDOFF.md index 41e12a69..d5a01bd6 100644 --- a/docs/QUOTA_V2_GENESIS_QUARANTINE_HANDOFF.md +++ b/docs/QUOTA_V2_GENESIS_QUARANTINE_HANDOFF.md @@ -1178,3 +1178,32 @@ rejection, repetition, disconnect, deadline and the hosted guard. The enrolled transport is a fixture in those tests; they do not yet prove the real Nexus SQL stop witness across the private boundary or serve a public TLS listener. No installer or service uses this module. + +### Exact read-only meter route across Docker mount namespaces + +The first two-installed-Node native TLS rehearsal discovered the kernel +rejects `open_tree(OPEN_TREE_CLONE)` with EINVAL when the retained meter +directory FD belongs to a different mount namespace, even as root. The +original meter's Unix sockets live on its own Docker /dev/shm, unlike the +same-mount local fixture. The signed route capsule still independently pins +the original actual pidfs object and source inode. + +For a foreign mount only, the dormant route bundle uses a single-use +child that closes all unrelated inherited descriptors, enters the exact +already-pinned meter pidfd's mount namespace, clones the already-open meter +directory (no pathname resolution or bind mount), applies the same +read-only/nosuid/nodev/noexec attributes and transfers exactly one FD over +a credential-checked connected seqpacket pair. The child exits before +acceptance. In its unchanged private mount namespace the supervisor +independently verifies the actual source/view inode, distinct mount ID, +kernel VFS flags, CLOEXEC, original live pidfd and both mount namespace +identities. Only the detached view and sealed manifest are passed to the +native child; it receives neither a pidfd nor any namespace descriptor. +No host mount is modified and no weaker fallback, route, public port or +production authorization is introduced. + +A real separate tmpfs mount namespace test requires direct open_tree to +fail, the exact detached read-only view to succeed, actual Unix stream +peer authentication, rejection of a wrong pidfd, foreign source and dead +meter, and an unchanged supervisor mount namespace. The local structural +variant cannot replace the mandatory hosted real-peer test. diff --git a/experiments/quota-v2-physical-stop/public_tls_namespace_route.py b/experiments/quota-v2-physical-stop/public_tls_namespace_route.py index 685e750e..f1070833 100644 --- a/experiments/quota-v2-physical-stop/public_tls_namespace_route.py +++ b/experiments/quota-v2-physical-stop/public_tls_namespace_route.py @@ -56,7 +56,8 @@ def __init__(self, original): if original.ensure_current() is not None: raise ValueError("original route evidence cannot authorize ingress") self._peer = peers.capture_original(original._pidfd, original._pid) - self._view, self._mount = mounts.readonly_view(original._meter_fd) + self._view, self._mount = mounts.readonly_meter_view( + original._meter_fd, original._pidfd, original._pid) names = set(os.listdir(self._view)) lock_names = {tag + ".lock" for tag in original._tags} # Standalone lockless kernel fixtures remain valid. Real Xray diff --git a/experiments/quota-v2-physical-stop/public_tls_route_mount.py b/experiments/quota-v2-physical-stop/public_tls_route_mount.py index 7aa1a27d..bbfe7da1 100644 --- a/experiments/quota-v2-physical-stop/public_tls_route_mount.py +++ b/experiments/quota-v2-physical-stop/public_tls_route_mount.py @@ -5,7 +5,12 @@ authority. No weaker pathname-only fallback is permitted. """ import ctypes +import errno import os +import signal +import socket +import struct +import time AT_EMPTY_PATH = 0x1000 OPEN_TREE_CLONE = 1 @@ -57,8 +62,12 @@ def check_view(source_fd, readonly_fd, expected_mount): raise ValueError("private TLS route descriptor is not its pinned read-only mount") -def readonly_view(source_fd): - """Return a CLOEXEC directory FD on a detached mount, same source inode.""" +def _clone_readonly(source_fd): + """Clone and restrict an exact FD in its own mount namespace. + + No pathname or procfs read is needed while accessing the foreign mount. + The caller must independently check the returned descriptor. + """ if os.geteuid() != 0: raise ValueError("root required for detached private route mount") libc = _libc() @@ -75,12 +84,142 @@ def readonly_view(source_fd): # open_tree yields O_PATH. Reopen the exact detached mount's root # through that FD for listdir/fstat; never reopen the original path. view = os.open(".", DIR_FLAGS, dir_fd=tree) - identity = mount_id(tree) - check_view(source_fd, view, identity) - result = view, identity + result = view view = None return result finally: if view is not None: os.close(view) os.close(tree) + + +def readonly_view(source_fd): + """Return a CLOEXEC directory FD on a detached mount, same source inode.""" + view = _clone_readonly(source_fd) + try: + identity = mount_id(view) + check_view(source_fd, view, identity) + return view, identity + except BaseException: + os.close(view) + raise + + +def _close_except(keep): + for entry in os.listdir("/proc/self/fd"): + fd = int(entry) + if fd not in keep: + try: + os.close(fd) + except OSError as exc: + # listdir's own temporary descriptor is already closed. + if exc.errno != errno.EBADF: + raise + + +def readonly_meter_view(source_fd, pidfd, pid): + """Clone an actual original meter directory across mount namespaces. + + The kernel rejects open_tree(CLONE) on a mount outside the caller's + namespace. A single-use forked helper enters the exact pinned *pidfd*'s + mount namespace, clones only the already-open source FD and restricts + the detached tree before returning one FD. The supervisor never changes + namespaces; neither the helper nor the native process may retain an + original namespace/root, writable route, relay or arbitrary other FD. + No bind mount, path reopen, mutable remount or fallback is permitted. + """ + import public_tls_peer_identity as peers + + if (os.geteuid() != 0 or os.getegid() != 0 + or len(os.listdir('/proc/self/task')) != 1 + or type(source_fd) is not int or source_fd < 3 + or os.get_inheritable(source_fd) or source_fd == pidfd): + raise ValueError("single-thread root and private meter descriptors required") + peer = peers.capture_original(pidfd, pid) + own_ns = os.readlink('/proc/self/ns/mnt') + meter_ns = os.readlink(f'/proc/{pid}/ns/mnt') + if own_ns == meter_ns: + view, identity = readonly_view(source_fd) + try: + if (os.readlink(f'/proc/{pid}/ns/mnt') != meter_ns + or peers.capture_original(pidfd, pid) != peer): + raise ValueError("original meter changed during same-namespace clone") + return view, identity + except BaseException: + os.close(view) + raise + + creds = struct.Struct('3i') + integer = struct.Struct('i') + parent, child = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET | socket.SOCK_CLOEXEC) + helper = None + received = [] + try: + parent.setsockopt(socket.SOL_SOCKET, socket.SO_PASSCRED, 1) + parent.settimeout(3) + helper = os.fork() + if helper == 0: + try: + # Close copies of ALL supervisor-owned inputs except the + # two already-pinned meter FDs and the one return socket, + # *before* entering the original meter's mount namespace. + parent.close() + _close_except({source_fd, pidfd, child.fileno()}) + os.setns(pidfd, os.CLONE_NEWNS) + view = _clone_readonly(source_fd) + if child.sendmsg([b'R'], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, + integer.pack(view))]) != 1: + os._exit(1) + os.close(view) + os._exit(0) + except BaseException: + os._exit(1) + child.close() + raw, ancillary, flags, _ = parent.recvmsg(2, + socket.CMSG_SPACE(creds.size) + socket.CMSG_SPACE(integer.size), + socket.MSG_CMSG_CLOEXEC) + credentials = [] + unexpected = False + for level, kind, data in ancillary: + if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS: + # Close even partial received descriptors on error. + for offset in range(0, len(data)-integer.size+1, integer.size): + received.append(integer.unpack_from(data, offset)[0]) + unexpected |= len(data) != integer.size + elif level == socket.SOL_SOCKET and kind == socket.SCM_CREDENTIALS and len(data) == creds.size: + credentials.append(creds.unpack(data)) + else: + unexpected = True + if (raw != b'R' or flags & (socket.MSG_TRUNC | socket.MSG_CTRUNC) + or unexpected or len(received) != 1 or credentials != [(helper, 0, 0)]): + raise ValueError("invalid exact detached meter FD transfer") + # Child must have exited before the supervisor can accept this view. + end = time.monotonic() + 1 + while True: + waited, status = os.waitpid(helper, os.WNOHANG) + if waited: + helper = None + if status != 0: + raise ValueError("detached meter helper failed") + break + if time.monotonic() >= end: + raise ValueError("detached meter helper did not exit") + time.sleep(0.01) + view = received[0] + identity = mount_id(view) + check_view(source_fd, view, identity) + if (os.readlink('/proc/self/ns/mnt') != own_ns + or os.readlink(f'/proc/{pid}/ns/mnt') != meter_ns + or peers.capture_original(pidfd, pid) != peer): + raise ValueError("original meter or supervisor mount namespace changed") + received.clear() + return view, identity + finally: + parent.close() + child.close() + for fd in received: + os.close(fd) + if helper is not None and helper > 0: + # The unreaped directly-owned PID cannot be recycled. + os.kill(helper, signal.SIGKILL) + os.waitpid(helper, 0) diff --git a/tests/test_quota_v2_public_tls_foreign_mount.py b/tests/test_quota_v2_public_tls_foreign_mount.py new file mode 100644 index 00000000..de6fc0fe --- /dev/null +++ b/tests/test_quota_v2_public_tls_foreign_mount.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Actual foreign mount namespace and exact detached original Unix peer.""" +import errno +import os +from pathlib import Path +import select +import socket +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'experiments/quota-v2-physical-stop')) +import public_tls_route_mount as mounts +import public_tls_peer_identity as peers + + +METER = r""" +import os, socket, stat, subprocess, sys +from pathlib import Path +root = Path(sys.argv[1]) +subprocess.run(['mount','-t','tmpfs','-o','mode=0700,nosuid,nodev,noexec','tmpfs',str(root)],check=True,timeout=5) +directory = root / 'only-meter' +directory.mkdir(mode=0o700) +if sys.argv[2] == 'structure': + os.mknod(directory / 'vless-main',stat.S_IFSOCK | 0o600) + print('foreign_meter_ready',flush=True) + assert sys.stdin.readline() == 'stop\n' + sys.exit(0) +with socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) as sock: + sock.bind(str(directory / 'vless-main')) + (directory / 'vless-main').chmod(0o600) + sock.listen(1) + print('foreign_meter_ready',flush=True) + conn,_ = sock.accept() + with conn: + assert conn.recv(1) == b'X' + conn.sendall(b'Y') + assert sys.stdin.readline() == 'stop\n' +""" + + +class ForeignMountTests(unittest.TestCase): + def setUp(self): + if os.geteuid() != 0: + self.skipTest('root mount namespace qualification required') + self.temp = tempfile.TemporaryDirectory(prefix='xmesh-foreign-mount-') + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.local = os.readlink('/proc/self/ns/mnt') + self.structure = os.environ.get('XMESH_TEST_FOREIGN_MOUNT_STRUCTURE') == '1' + if self.structure: + self.assertNotEqual(os.environ.get('GITHUB_ACTIONS'),'true') + self.child = subprocess.Popen(['unshare','--mount','--propagation','private', + sys.executable,'-I','-B','-c',METER,str(self.root),'structure' if self.structure else 'live'], + stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True) + self.addCleanup(self.reap) + self.assertTrue(select.select([self.child.stdout],[],[],8)[0]) + ready = self.child.stdout.readline().strip() + if not ready: + self.child.wait(timeout=5) + self.fail('foreign meter exited: '+self.child.stderr.read()) + self.assertEqual(ready,'foreign_meter_ready') + self.foreign = os.readlink(f'/proc/{self.child.pid}/ns/mnt') + self.assertNotEqual(self.local,self.foreign) + self.assertFalse((self.root/'only-meter').exists()) + self.source = os.open(f'/proc/{self.child.pid}/root{self.root}/only-meter',mounts.DIR_FLAGS) + self.addCleanup(os.close,self.source) + self.pidfd = os.pidfd_open(self.child.pid) + self.addCleanup(os.close,self.pidfd) + + def reap(self): + if self.child.poll() is None: + self.child.kill() + self.child.communicate(timeout=5) + + def test_exact_foreign_mount_fd_and_live_peer_without_supervisor_setns(self): + with self.assertRaises(OSError) as denied: + mounts.readonly_view(self.source) + self.assertEqual(denied.exception.errno,errno.EINVAL) + view, identity = mounts.readonly_meter_view(self.source,self.pidfd,self.child.pid) + try: + self.assertEqual(os.readlink('/proc/self/ns/mnt'),self.local) + self.assertFalse((self.root/'only-meter').exists()) + self.assertIsNone(mounts.check_view(self.source,view,identity)) + self.assertEqual(os.listdir(view),['vless-main']) + self.assertEqual(os.fstat(view).st_ino,os.stat('..',dir_fd=view).st_ino) + self.assertFalse(os.get_inheritable(view)) + with self.assertRaises(OSError) as readonly: + os.unlink('vless-main',dir_fd=view) + self.assertEqual(readonly.exception.errno,errno.EROFS) + if not self.structure: + expected = peers.capture_original(self.pidfd,self.child.pid) + with socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) as conn: + conn.settimeout(2) + conn.connect(f'/proc/self/fd/{view}/vless-main') + self.assertIsNone(peers.verify_connected_peer(conn,expected)) + conn.sendall(b'X') + self.assertEqual(conn.recv(1),b'Y') + self.child.stdin.write('stop\n') + self.child.stdin.flush() + self.assertEqual(self.child.wait(timeout=5),0) + finally: + os.close(view) + + def test_wrong_pinned_pid_or_foreign_source_is_rejected(self): + own = os.pidfd_open(os.getpid()) + local = os.open(self.root,mounts.DIR_FLAGS) + try: + with self.assertRaises(ValueError): + mounts.readonly_meter_view(self.source,own,self.child.pid) + with self.assertRaises(ValueError): + mounts.readonly_meter_view(local,self.pidfd,self.child.pid) + self.assertEqual(os.readlink('/proc/self/ns/mnt'),self.local) + finally: + os.close(own) + os.close(local) + self.child.kill() + self.child.wait(timeout=5) + with self.assertRaises(ValueError): + mounts.readonly_meter_view(self.source,self.pidfd,self.child.pid) + + +if __name__ == '__main__': + unittest.main()