From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796094750; b=sC8+DFs4FWW7mhN7fIXzr2RAn5z2bO9WhUhQG1S3vHF1aewvx8zbsA8RdiRy2DvtZQM/ DUcO11qISmpohEv2K6rO101WhUyrf0ANwlT8jna9JAGiK1/bVL5som8mxmAeHIG+FFJ7K VAeT5k8Za/gFzqeGIUIOzkyUVp2pVHWkX7ZLlcWvfjkQ+yQ+w5qeroMpUY3yD35A/6/Tw k3XtPxT+c+4NkxGVPVinDhMVKn8biZTEbDWgh4MUZcMLkdVHecgM/8xq7izJU/GwdnuKv AxY6Z2EFy2BHrkjvE2U4WCDHWTKKD1B/jVHILrl0ESvRto0GfvFnW6hjn2D0cp2cxGQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796094750; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Transfer-Encoding; bh=DhAdj3y44AG9kffnOmaRq0PhtKyIy2yjJUb1Sq3CkdY=; b=d68L6yIoQzAoXAAdAy8eQaatMULqRMgExAwRvzYNeMO6a3pHzEleOnJthcp6t73RmL4y 8WOCfbMcHe69wMI0BP7sGPV9R8ucaj1wulUy175CKyWCvPeCjgUnRKLk5nKsR4FjVQcgX rNm/N2nKBKC/5vedtxaGewbiN2nyUCLc2WOU60XFFpzgNI+ZhhQytvQuH+31n/DXMzhcW iuyhLtrkrnvFeUP1kTa252t4Uc1C2Q0oLj+Qqgokd3WtCLOK2RVIHk7h/IZ32dheQn9k5 IXPxAi9vpYFiI8f6w6INjmXk/wqyqWdqr2GzKO9FGfnWUuxHEo6WjWmpGmK0NVU8/fA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=bUNgzW+6; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with UTF8SMTPS id 3B5F2606A332; Tue, 1 Dec 2026 03:12:29 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.a=rsa-sha256 header.s=k20260515 header.b=bUNgzW+6 Received: by smtp.kernel.org (Postfix) with UTF8SMTPSA id 76DE41F0089F; Tue, 1 Dec 2026 03:12:28 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1796094749; bh=DhAdj3y44AG9kffnOmaRq0PhtKyIy2yjJUb1Sq3CkdY=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=bUNgzW+6k+cLg4DPKvsnAyOqt7kPu24CXSeiNpVSsEzb5nZlqPdmVBpO1RhyQl1t8 SYHAQHmKrkQ3dFyrZpmvEp/lFr90XCnl/afEI62lf2VrGsSS9DJi/rS1gSP6umTLoL KnTV7T0MKHJbwsAiy3sN3+7zMCAN2HqAqMrPnxT6nKu4CvrO8CRzkk/3wLwLKz4z3I eXg6/1g0pWS74MXdXlPZzTnIV28QZH8X0PY5XDpJgGYRIQRwYmcdHW84DFSoQzbjRM FCE2lxMiLXLI9DDK/q+lAeWKhJo4Zx0q4AkV1SOAn+5RBE6ZzUKh6TksFNYLCITnmT xjql1HzvVTsRw== From: Jarkko Sakkinen To: fsdevel@vger.kernel.org Cc: Jarkko Sakkinen , bpf@vger.kernel.org, containers@lists.linux.dev, linux-api@vger.kernel.org, linux-arch@vger.kernel.org, linux-doc@vger.kernel.org, linux-fsdevel@vger.kernel.org, linux-integrity@vger.kernel.org, linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-mm@kvack.org, linux-security-module@vger.kernel.org, Aleksa Sarai , Alexander Mikhalitsyn , Alexander Viro , Alexei Starovoitov , Andrew Morton , Andrii Nakryiko , Andy Lutomirski , Arnd Bergmann , Baolin Wang , Ben Segall , Christian Brauner , Daniel Borkmann , David Hildenbrand , David Howells , David Woodhouse , Davidlohr Bueso , Dietmar Eggemann , Eduard Zingerman , Emil Tsalapatis , Eric Biggers , Georgia Garcia , Giuseppe Scrivano , =?UTF-8?q?G=C3=BCnther=20Noack?= , Hugh Dickins , Ihor Solodrai , Ingo Molnar , James Morris , Jan Kara , Jason Gunthorpe , Jeff Layton , Jiri Olsa , John Johansen , Jonathan Corbet , Josef Bacik , Juri Lelli , Kees Cook , K Prateek Nayak , KP Singh , Kumar Kartikeya Dwivedi , Lennart Poettering , "Liam R. Howlett" , Manfred Spraul , Martin KaFai Lau , Matt Bobrowski , Mel Gorman , Michal Hocko , =?UTF-8?q?Micka=C3=ABl=20Sala=C3=BCn?= , Mike Rapoport , Neal Gompa , Oleg Nesterov , Paul Moore , Pavel Tikhomirov , Peter Zijlstra , Randy Dunlap , "Serge E. Hallyn" , Serge Hallyn , Shuah Khan , Song Liu , Stephen Smalley , Steven Rostedt , Valentin Schneider , Vincent Guittot , Yonghong Song , Zygmunt Krynicki Subject: [RFC PATCH v9 28/29] selftests/nsexec: Add nsexec test suite Date: Tue, 1 Dec 2026 05:10:00 +0200 Message-ID: <20261201031002.593830-29-jarkko@kernel.org> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261201031002.593830-1-jarkko@kernel.org> References: <20261201031002.593830-1-jarkko@kernel.org> X-Mailing-List: linux-fsdevel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Add a model-based stochastic kselftest suite for nsexec_open(), NSEXEC_GET_NSFD, NSEXEC_SHARE_NSFD, waitid(P_NSEXEC), pidfd_send_signal(), userns_set_idmap(), FSCONFIG_SET_NSEXEC, MOVE_MOUNT_T_MNTNS, CLONE_INTO_NSEXEC, and Landlock namespace mediation. Drive lifecycle, ID-mapping, mount-tree, multi-cell supervisor, and Landlock scenarios from a seeded choice stream against a reference uAPI oracle. Each case is a pure function of the seed, scenario, and case index, and shrinking is bounded by attempt count, so NSEXEC_SEED and NSEXEC_CASE replay both a failure and its minimal trace. Signed-off-by: Jarkko Sakkinen --- tools/testing/selftests/Makefile | 1 + tools/testing/selftests/nsexec/Makefile | 7 + tools/testing/selftests/nsexec/cells.py | 1560 ++++++++++ tools/testing/selftests/nsexec/config | 13 + tools/testing/selftests/nsexec/machine.py | 333 ++ tools/testing/selftests/nsexec/oracle.py | 386 +++ tools/testing/selftests/nsexec/selftest.py | 2887 ++++++++++++++++++ tools/testing/selftests/nsexec/settings | 1 + tools/testing/selftests/nsexec/test_smoke.sh | 11 + 9 files changed, 5199 insertions(+) create mode 100644 tools/testing/selftests/nsexec/Makefile create mode 100644 tools/testing/selftests/nsexec/cells.py create mode 100644 tools/testing/selftests/nsexec/config create mode 100644 tools/testing/selftests/nsexec/machine.py create mode 100644 tools/testing/selftests/nsexec/oracle.py create mode 100755 tools/testing/selftests/nsexec/selftest.py create mode 100644 tools/testing/selftests/nsexec/settings create mode 100755 tools/testing/selftests/nsexec/test_smoke.sh diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile index 07c3719f8b04..3ec2bb6b9f6f 100644 --- a/tools/testing/selftests/Makefile +++ b/tools/testing/selftests/Makefile @@ -101,6 +101,7 @@ TARGETS += net/rds TARGETS += net/tcp_ao TARGETS += nfsd TARGETS += nolibc +TARGETS += nsexec TARGETS += pci_endpoint TARGETS += pcie_bwctrl TARGETS += perf_events diff --git a/tools/testing/selftests/nsexec/Makefile b/tools/testing/selftests/nsexec/Makefile new file mode 100644 index 000000000000..12f8598632d7 --- /dev/null +++ b/tools/testing/selftests/nsexec/Makefile @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0 +include ../lib.mk + +TEST_PROGS := test_smoke.sh +TEST_PROGS_EXTENDED := selftest.py +TEST_FILES := cells.py machine.py oracle.py +TEST_INCLUDES := ../kselftest/ksft.py diff --git a/tools/testing/selftests/nsexec/cells.py b/tools/testing/selftests/nsexec/cells.py new file mode 100644 index 000000000000..d138d44c4df5 --- /dev/null +++ b/tools/testing/selftests/nsexec/cells.py @@ -0,0 +1,1560 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Copyright (C) 2026 Opinsys Oy + +"""Low-level nsexec(2) syscall bindings and bottleneck-free Cells runtime.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from contextlib import suppress +import ctypes +from dataclasses import dataclass, field +from enum import IntEnum, IntFlag, StrEnum +import errno +import os +import platform +import select +import signal +import socket +import sys +import time +from types import TracebackType +from typing import Any, ClassVar, Final, NoReturn + +HOST_RUNTIME_DIRS: Final[tuple[str, ...]] = ( + "usr", + "bin", + "sbin", + "lib", + "lib32", + "lib64", + "libx32", + "etc", + "opt", + "nix", +) + +DEV_NODES: Final[tuple[str, ...]] = ( + "null", + "zero", + "full", + "random", + "urandom", + "tty", +) + + +class NsExecFlag(IntFlag): + NONE = 0 + AUTOKILL = 0x00000001 + DEFAULT = AUTOKILL + ALL = AUTOKILL + + +class CloneFlag(IntFlag): + NONE = 0 + NEWTIME = 0x00000080 + VM = 0x00000100 + FS = 0x00000200 + FILES = 0x00000400 + SIGHAND = 0x00000800 + PIDFD = 0x00001000 + VFORK = 0x00004000 + PARENT = 0x00008000 + THREAD = 0x00010000 + NEWNS = 0x00020000 + SYSVSEM = 0x00040000 + NEWCGROUP = 0x02000000 + NEWUTS = 0x04000000 + NEWIPC = 0x08000000 + NEWUSER = 0x10000000 + NEWPID = 0x20000000 + NEWNET = 0x40000000 + CLEAR_SIGHAND = 1 << 32 + INTO_CGROUP = 1 << 33 + AUTOREAP = 1 << 34 + NNP = 1 << 35 + PIDFD_AUTOKILL = 1 << 36 + EMPTY_MNTNS = 1 << 37 + INTO_NSEXEC = 1 << 38 + + +SHAREABLE_NSTYPES: Final[tuple[CloneFlag, ...]] = ( + CloneFlag.NEWCGROUP, + CloneFlag.NEWIPC, + CloneFlag.NEWUTS, + CloneFlag.NEWNET, + CloneFlag.NEWTIME, +) + +NS_NAMES: Final[Mapping[CloneFlag, str]] = { + CloneFlag.NEWNS: "mnt", + CloneFlag.NEWCGROUP: "cgroup", + CloneFlag.NEWUTS: "uts", + CloneFlag.NEWIPC: "ipc", + CloneFlag.NEWUSER: "user", + CloneFlag.NEWPID: "pid", + CloneFlag.NEWNET: "net", + CloneFlag.NEWTIME: "time", +} + + +class AtFlag(IntFlag): + NONE = 0 + EMPTY_PATH = 0x1000 + + +class MoveMountFlag(IntFlag): + F_EMPTY_PATH = 0x00000004 + T_MNTNS = 0x00000080 + SET_GROUP = 0x00000100 + BENEATH = 0x00000200 + CLONE = 0x00000400 + +class UsernsFlag(IntFlag): + NONE = 0 + SETGROUPS_ALLOWED = 1 << 0 + + +class MountAttrFlag(IntFlag): + NONE = 0 + RDONLY = 0x00000001 + NOSUID = 0x00000002 + NODEV = 0x00000004 + NOEXEC = 0x00000008 + +class UmountFlag(IntFlag): + NONE = 0 + DETACH = 2 + + +class ResolveFlag(IntFlag): + NONE = 0 + IN_ROOT = 0x10 + + +class FsconfigCmd(IntEnum): + SET_FLAG = 0 + SET_STRING = 1 + CMD_CREATE = 6 + CMD_RECONFIGURE = 7 + CMD_CREATE_EXCL = 8 + SET_NSEXEC = 9 + + +class PrctlOp(IntEnum): + GET_DUMPABLE = 3 + SET_DUMPABLE = 4 + SET_KEEPCAPS = 8 + GET_NO_NEW_PRIVS = 39 + + +class WaitIdType(IntEnum): + ALL = 0 + PID = 1 + PGID = 2 + PIDFD = 3 + NSEXEC = 4 + + +class PidfdInfoFlag(IntFlag): + PID = 1 << 0 + CREDS = 1 << 1 + CGROUPID = 1 << 2 + EXIT = 1 << 3 + + +class PidfdInfo(ctypes.Structure): + SIZE_VER3: ClassVar[int] = 88 + + mask: int + cgroupid: int + pid: int + tgid: int + ppid: int + ruid: int + rgid: int + euid: int + egid: int + suid: int + sgid: int + fsuid: int + fsgid: int + exit_code: int + coredump_mask: int + coredump_signal: int + coredump_code: int + coredump_pad: int + supported_mask: int + _fields_ = [ + ("mask", ctypes.c_uint64), + ("cgroupid", ctypes.c_uint64), + ("pid", ctypes.c_uint32), + ("tgid", ctypes.c_uint32), + ("ppid", ctypes.c_uint32), + ("ruid", ctypes.c_uint32), + ("rgid", ctypes.c_uint32), + ("euid", ctypes.c_uint32), + ("egid", ctypes.c_uint32), + ("suid", ctypes.c_uint32), + ("sgid", ctypes.c_uint32), + ("fsuid", ctypes.c_uint32), + ("fsgid", ctypes.c_uint32), + ("exit_code", ctypes.c_int32), + ("coredump_mask", ctypes.c_uint32), + ("coredump_signal", ctypes.c_uint32), + ("coredump_code", ctypes.c_uint32), + ("coredump_pad", ctypes.c_uint32), + ("supported_mask", ctypes.c_uint64), + ] + + @property + def decoded_exit(self) -> int | None: + if not (self.mask & int(PidfdInfoFlag.EXIT)): + return None + return os.waitstatus_to_exitcode(self.exit_code) + + +class CloneArgs(ctypes.Structure): + SIZE_VER2: ClassVar[int] = 88 + SIZE_VER3: ClassVar[int] = 96 + + flags: int + pidfd: int + child_tid: int + parent_tid: int + exit_signal: int + stack: int + stack_size: int + tls: int + set_tid: int + set_tid_size: int + cgroup: int + nsexec: int + _fields_ = [ + ("flags", ctypes.c_uint64), + ("pidfd", ctypes.c_uint64), + ("child_tid", ctypes.c_uint64), + ("parent_tid", ctypes.c_uint64), + ("exit_signal", ctypes.c_uint64), + ("stack", ctypes.c_uint64), + ("stack_size", ctypes.c_uint64), + ("tls", ctypes.c_uint64), + ("set_tid", ctypes.c_uint64), + ("set_tid_size", ctypes.c_uint64), + ("cgroup", ctypes.c_uint64), + ("nsexec", ctypes.c_uint64), + ] + + +class OpenHow(ctypes.Structure): + flags: int + mode: int + resolve: int + _fields_ = [ + ("flags", ctypes.c_uint64), + ("mode", ctypes.c_uint64), + ("resolve", ctypes.c_uint64), + ] + + +class UsernsIdmapExtent(ctypes.Structure): + first: int + lower_first: int + count: int + reserved: int + _fields_ = [ + ("first", ctypes.c_uint32), + ("lower_first", ctypes.c_uint32), + ("count", ctypes.c_uint32), + ("reserved", ctypes.c_uint32), + ] + + +class UsernsIdmap(ctypes.Structure): + SIZE_VER0: ClassVar[int] = 40 + + nr_uid_extents: int + nr_gid_extents: int + nr_projid_extents: int + reserved: int + uid_extents: int + gid_extents: int + projid_extents: int + _fields_ = [ + ("nr_uid_extents", ctypes.c_uint32), + ("nr_gid_extents", ctypes.c_uint32), + ("nr_projid_extents", ctypes.c_uint32), + ("reserved", ctypes.c_uint32), + ("uid_extents", ctypes.c_uint64), + ("gid_extents", ctypes.c_uint64), + ("projid_extents", ctypes.c_uint64), + ] + + +class CapHeader(ctypes.Structure): + VERSION_3: ClassVar[int] = 0x20080522 + + version: int + pid: int + _fields_ = [("version", ctypes.c_uint32), ("pid", ctypes.c_int32)] + + +class CapData(ctypes.Structure): + effective: int + permitted: int + inheritable: int + _fields_ = [ + ("effective", ctypes.c_uint32), + ("permitted", ctypes.c_uint32), + ("inheritable", ctypes.c_uint32), + ] + + +_LEGACY_SYSCALLS: Final[dict[str, tuple[int, int, int, int]]] = { + "x86_64": (155, 166, 247, 322), + "i386": (217, 52, 284, 358), + "arm": (218, 52, 280, 387), + "ppc": (203, 52, 272, 362), + "s390": (217, 52, 281, 354), + "sparc": (146, 45, 279, 350), + "parisc": (67, 52, 235, 342), + "m68k": (217, 52, 277, 355), + "microblaze": (217, 52, 284, 388), + "sh": (217, 52, 284, 376), + "xtensa": (175, 171, 122, 341), + "alpha": (374, 22, 438, 513), + "mips64": (5151, 5161, 5237, 5316), + "mipsn32": (6151, 6161, 6241, 6320), + "mips32": (4216, 4052, 4278, 4356), + "generic": (41, 39, 95, 281), +} + + +class Sys: + AT_FDCWD: Final[int] = -100 + FSOPEN_CLOEXEC: Final[int] = 0x00000001 + FSMOUNT_CLOEXEC: Final[int] = 0x00000001 + CAP_SETGID: Final[int] = 6 + CAP_SETUID: Final[int] = 7 + _WIDE_IOC: Final[tuple[str, ...]] = ( + "alpha", + "mips", + "powerpc", + "ppc", + "sparc", + ) + + _NR: ClassVar[dict[str, int]] + _LIBC: ClassVar[ctypes.CDLL] + + @classmethod + def _is_wide_ioc(cls) -> bool: + return platform.machine().lower().startswith(cls._WIDE_IOC) + + @classmethod + def ioc(cls, direction: int, magic: int, nr: int, size: int) -> int: + dirshift = 16 + (13 if cls._is_wide_ioc() else 14) + return (direction << dirshift) | (magic << 8) | nr | (size << 16) + + @classmethod + def io(cls, magic: int, nr: int) -> int: + return cls.ioc(1 if cls._is_wide_ioc() else 0, magic, nr, 0) + + @classmethod + def iowr(cls, magic: int, nr: int, size: int) -> int: + return cls.ioc(6 if cls._is_wide_ioc() else 3, magic, nr, size) + + @staticmethod + def _build_syscall_numbers() -> dict[str, int]: + mach = platform.machine().lower() + ptr_sz = ctypes.sizeof(ctypes.c_void_p) + multi = getattr(sys.implementation, "_multiarch", "") + base = 0 + key = "generic" + + if mach.startswith("alpha"): + base, key = 110, "alpha" + elif mach.startswith("mips"): + if ptr_sz == 8: + base, key = 5000, "mips64" + elif "abin32" in multi: + base, key = 6000, "mipsn32" + else: + base, key = 4000, "mips32" + elif mach == "x86_64" and ptr_sz == 4 and "x32" in multi: + base = 0x40000000 + piv, umt, wid, exv = ( + base + 155, + base + 166, + base + 529, + base + 545, + ) + else: + if mach == "x86_64" and ptr_sz == 8: + key = "x86_64" + elif mach in ("i386", "i486", "i586", "i686", "x86_64"): + key = "i386" + elif mach in ("aarch64", "arm64") and ptr_sz == 8: + key = "generic" + elif mach.startswith(("arm", "aarch64")): + key = "arm" + elif mach.startswith(("ppc", "powerpc")): + key = "ppc" + elif mach.startswith("s390"): + key = "s390" + elif mach.startswith("sparc"): + key = "sparc" + elif mach.startswith(("parisc", "hppa")): + key = "parisc" + elif mach in ("m68k", "xtensa"): + key = mach + elif mach.startswith("microblaze"): + key = "microblaze" + elif mach.startswith("sh"): + key = "sh" + + if base != 0x40000000: + piv, umt, wid, exv = _LEGACY_SYSCALLS[key] + + return { + "pivot_root": piv, + "umount2": umt, + "waitid": wid, + "execveat": exv, + "pidfd_send_signal": base + 424, + "move_mount": base + 429, + "fsopen": base + 430, + "fsconfig": base + 431, + "fsmount": base + 432, + "clone3": base + 435, + "openat2": base + 437, + "landlock_create_ruleset": base + 444, + "landlock_add_rule": base + 445, + "landlock_restrict_self": base + 446, + "userns_set_idmap": base + 473, + "nsexec_open": base + 474, + } + + @staticmethod + def _os_err() -> NoReturn: + err = ctypes.get_errno() + raise OSError(err, os.strerror(err)) + + @staticmethod + def _cstr(val: str | bytes) -> bytes: + return val if isinstance(val, bytes) else os.fsencode(val) + + @classmethod + def fork(cls) -> int: + sys.stdout.flush() + sys.stderr.flush() + return os.fork() + + @classmethod + def syscall(cls, name: str, *args: Any) -> int: + ret: int = cls._LIBC.syscall(ctypes.c_long(cls._NR[name]), *args) + if ret < 0: + cls._os_err() + return int(ret) + + @classmethod + def ioctl(cls, fd: int, cmd: int, arg: int = 0) -> int: + ret: int = cls._LIBC.ioctl( + ctypes.c_int(fd), ctypes.c_ulong(int(cmd)), ctypes.c_ulong(arg) + ) + if ret < 0: + cls._os_err() + return int(ret) + + @classmethod + def pidfd_get_info( + cls, pidfd: int, mask: PidfdInfoFlag | int = PidfdInfoFlag.EXIT + ) -> PidfdInfo: + info = PidfdInfo(mask=int(mask)) + ret: int = cls._LIBC.ioctl( + ctypes.c_int(pidfd), + ctypes.c_ulong(int(Ioctl.PIDFD_GET_INFO)), + ctypes.byref(info), + ) + if ret < 0: + cls._os_err() + return info + + @classmethod + def fsopen(cls, fsname: str | bytes, flags: int = FSOPEN_CLOEXEC) -> int: + return cls.syscall( + "fsopen", ctypes.c_char_p(cls._cstr(fsname)), ctypes.c_uint(flags) + ) + + @classmethod + def fsconfig( + cls, + fsfd: int, + cmd: FsconfigCmd, + key: str | bytes | None = None, + value: str | bytes | None = None, + aux: int = 0, + ) -> None: + k_ptr = ( + ctypes.c_char_p(cls._cstr(key)) + if key is not None + else ctypes.c_void_p(0) + ) + v_ptr = ( + ctypes.c_char_p(cls._cstr(value)) + if value is not None + else ctypes.c_void_p(0) + ) + cls.syscall( + "fsconfig", + ctypes.c_int(fsfd), + ctypes.c_uint(int(cmd)), + k_ptr, + v_ptr, + ctypes.c_int(aux), + ) + + @classmethod + def fsmount( + cls, + fsfd: int, + flags: int = FSMOUNT_CLOEXEC, + attr_flags: MountAttrFlag = MountAttrFlag.NONE, + ) -> int: + return cls.syscall( + "fsmount", + ctypes.c_int(fsfd), + ctypes.c_uint(flags), + ctypes.c_uint(int(attr_flags)), + ) + + @classmethod + def move_mount( + cls, + from_dfd: int, + from_path: str | bytes, + to_dfd: int, + to_path: str | bytes, + flags: MoveMountFlag | int, + ) -> None: + cls.syscall( + "move_mount", + ctypes.c_int(from_dfd), + ctypes.c_char_p(cls._cstr(from_path)), + ctypes.c_int(to_dfd), + ctypes.c_char_p(cls._cstr(to_path)), + ctypes.c_uint(int(flags)), + ) + + @classmethod + def openat2( + cls, + dfd: int, + path: str | bytes, + flags: int, + mode: int = 0, + resolve: ResolveFlag = ResolveFlag.NONE, + ) -> int: + how = OpenHow(flags=flags, mode=mode, resolve=int(resolve)) + return cls.syscall( + "openat2", + ctypes.c_int(dfd), + ctypes.c_char_p(cls._cstr(path)), + ctypes.byref(how), + ctypes.c_size_t(ctypes.sizeof(how)), + ) + + @classmethod + def execveat( + cls, + dfd: int, + path: str | bytes, + argv: Sequence[str], + envp: Mapping[str, str] | Sequence[str] | None = None, + flags: AtFlag = AtFlag.NONE, + ) -> NoReturn: + c_argv = (ctypes.c_char_p * (len(argv) + 1))( + *[cls._cstr(a) for a in argv], None + ) + if envp is None: + env_items = [f"{k}={v}" for k, v in os.environ.items()] + elif isinstance(envp, Mapping): + env_items = [f"{k}={v}" for k, v in envp.items()] + else: + env_items = list(envp) + c_envp = (ctypes.c_char_p * (len(env_items) + 1))( + *[cls._cstr(e) for e in env_items], None + ) + cls.syscall( + "execveat", + ctypes.c_int(dfd), + ctypes.c_char_p(cls._cstr(path)), + c_argv, + c_envp, + ctypes.c_int(int(flags)), + ) + cls._os_err() + + @classmethod + def pivot_root(cls, new_root: str | bytes, put_old: str | bytes) -> None: + cls.syscall( + "pivot_root", + ctypes.c_char_p(cls._cstr(new_root)), + ctypes.c_char_p(cls._cstr(put_old)), + ) + + @classmethod + def umount2( + cls, target: str | bytes, flags: UmountFlag = UmountFlag.NONE + ) -> None: + cls.syscall( + "umount2", + ctypes.c_char_p(cls._cstr(target)), + ctypes.c_int(int(flags)), + ) + + @classmethod + def setgroups_empty(cls) -> None: + ret: int = cls._LIBC.setgroups(ctypes.c_size_t(0), ctypes.c_void_p(0)) + if ret < 0: + cls._os_err() + + @classmethod + def unshare(cls, flags: CloneFlag | int) -> None: + ret: int = cls._LIBC.unshare(ctypes.c_int(int(flags))) + if ret < 0: + cls._os_err() + + @classmethod + def setns(cls, fd: int, nstype: CloneFlag | int = 0) -> None: + ret: int = cls._LIBC.setns(ctypes.c_int(fd), ctypes.c_int(int(nstype))) + if ret < 0: + cls._os_err() + + @classmethod + def drop_to_setid_helper(cls, uid: int) -> None: + cls.prctl(PrctlOp.SET_KEEPCAPS, 1) + try: + cls.setgroups_empty() + except OSError as exc: + if exc.errno != errno.EPERM: + raise + os.setresgid(uid, uid, uid) + os.setresuid(uid, uid, uid) + hdr = CapHeader(version=CapHeader.VERSION_3, pid=0) + mask = (1 << cls.CAP_SETGID) | (1 << cls.CAP_SETUID) + data = (CapData * 2)( + CapData(effective=mask, permitted=mask, inheritable=0), + CapData(effective=0, permitted=0, inheritable=0), + ) + ret: int = cls._LIBC.capset(ctypes.byref(hdr), ctypes.byref(data)) + if ret < 0: + cls._os_err() + cls.prctl(PrctlOp.SET_DUMPABLE, 1) + + @classmethod + def prctl( + cls, + option: PrctlOp, + arg2: int = 0, + arg3: int = 0, + arg4: int = 0, + arg5: int = 0, + ) -> int: + ret: int = cls._LIBC.prctl( + ctypes.c_int(int(option)), + ctypes.c_ulong(arg2), + ctypes.c_ulong(arg3), + ctypes.c_ulong(arg4), + ctypes.c_ulong(arg5), + ) + if ret < 0: + cls._os_err() + return int(ret) + + @classmethod + def clone3(cls, args: CloneArgs, size: int | None = None) -> int: + actual = ctypes.sizeof(args) if size is None else size + sys.stdout.flush() + sys.stderr.flush() + return cls.syscall( + "clone3", ctypes.byref(args), ctypes.c_size_t(actual) + ) + + @staticmethod + def _extent_array( + extents: Sequence[tuple[int, int, int]], + ) -> ctypes.Array[UsernsIdmapExtent] | None: + if not extents: + return None + arr_t = UsernsIdmapExtent * len(extents) + return arr_t( + *[ + UsernsIdmapExtent( + first=first, lower_first=lower, count=count, reserved=0 + ) + for first, lower, count in extents + ] + ) + + @classmethod + def pidfd_send_signal( + cls, pidfd: int, sig: int, info_addr: int = 0, flags: int = 0 + ) -> None: + cls.syscall( + "pidfd_send_signal", + ctypes.c_int(pidfd), + ctypes.c_int(sig), + ctypes.c_void_p(info_addr), + ctypes.c_uint(flags), + ) + + @classmethod + def waitid_raw( + cls, + which: int, + upid: int, + infop_addr: int, + options: int, + ru_addr: int = 0, + ) -> None: + cls.syscall( + "waitid", + ctypes.c_int(which), + ctypes.c_int(upid), + ctypes.c_void_p(infop_addr), + ctypes.c_int(options), + ctypes.c_void_p(ru_addr), + ) + + @classmethod + def userns_set_idmap_raw( + cls, + userns_fd: int, + map_addr: int, + size: int = UsernsIdmap.SIZE_VER0, + flags: int = 0, + ) -> None: + cls.syscall( + "userns_set_idmap", + ctypes.c_int(userns_fd), + ctypes.c_void_p(map_addr), + ctypes.c_size_t(size), + ctypes.c_uint(flags), + ) + + @classmethod + def set_userns_idmap( + cls, + userns_fd: int, + uid_extents: Sequence[tuple[int, int, int]] = (), + gid_extents: Sequence[tuple[int, int, int]] = (), + projid_extents: Sequence[tuple[int, int, int]] = (), + *, + reserved: int = 0, + size: int | None = None, + flags: UsernsFlag | int = UsernsFlag.NONE, + ) -> None: + u_arr = cls._extent_array(uid_extents) + g_arr = cls._extent_array(gid_extents) + p_arr = cls._extent_array(projid_extents) + req = UsernsIdmap( + nr_uid_extents=len(uid_extents), + nr_gid_extents=len(gid_extents), + nr_projid_extents=len(projid_extents), + reserved=reserved, + uid_extents=ctypes.addressof(u_arr) if u_arr is not None else 0, + gid_extents=ctypes.addressof(g_arr) if g_arr is not None else 0, + projid_extents=ctypes.addressof(p_arr) if p_arr is not None else 0, + ) + cls.userns_set_idmap_raw( + userns_fd, + ctypes.addressof(req), + ctypes.sizeof(req) if size is None else size, + int(flags), + ) + + @staticmethod + def close_fd(fd: int) -> int: + if fd >= 0: + with suppress(OSError): + os.close(fd) + return -1 + + +Sys._NR = Sys._build_syscall_numbers() +Sys._LIBC = ctypes.CDLL(None, use_errno=True) +Sys._LIBC.syscall.restype = ctypes.c_long + + +class Ioctl(IntEnum): + NSEXEC_GET_NSFD = Sys.io(0xB9, 0x01) + NSEXEC_SHARE_NSFD = Sys.io(0xB9, 0x02) + NS_GET_USERNS = Sys.io(0xB7, 0x01) + NS_GET_PARENT = Sys.io(0xB7, 0x02) + NS_GET_NSTYPE = Sys.io(0xB7, 0x03) + PIDFD_GET_CGROUP_NAMESPACE = Sys.io(0xFF, 1) + PIDFD_GET_IPC_NAMESPACE = Sys.io(0xFF, 2) + PIDFD_GET_MNT_NAMESPACE = Sys.io(0xFF, 3) + PIDFD_GET_NET_NAMESPACE = Sys.io(0xFF, 4) + PIDFD_GET_PID_NAMESPACE = Sys.io(0xFF, 5) + PIDFD_GET_TIME_NAMESPACE = Sys.io(0xFF, 7) + PIDFD_GET_USER_NAMESPACE = Sys.io(0xFF, 9) + PIDFD_GET_UTS_NAMESPACE = Sys.io(0xFF, 10) + PIDFD_GET_INFO = Sys.iowr(0xFF, 11, PidfdInfo.SIZE_VER3) + +@dataclass(frozen=True) +class WaitResult: + pid: int + status: int = 0 + code: int = 0 + uid: int = 0 + + @property + def exit_code(self) -> int | None: + if self.pid <= 0: + return None + if self.code == os.CLD_EXITED: + return self.status + if self.code in (os.CLD_KILLED, os.CLD_DUMPED): + return -self.status + return os.waitstatus_to_exitcode(self.status) + + +@dataclass +class Session: + """Autoreaped pidfd workload session inside a running Cell.""" + + pid: int + pidfd: int + autokill: bool = False + _cached_exit: int | None = field(default=None, init=False, repr=False) + + def fileno(self) -> int: + return self.pidfd + + def __enter__(self) -> Session: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() + + def poll(self) -> bool: + if self._cached_exit is not None: + return True + if self.pidfd < 0: + return False + poller = select.poll() + poller.register(self.pidfd, select.POLLIN) + return bool(poller.poll(0)) + + def wait(self, timeout: float = 5.0) -> int: + if self._cached_exit is not None: + return self._cached_exit + if self.pidfd < 0: + raise OSError(errno.EBADF, os.strerror(errno.EBADF)) + poller = select.poll() + poller.register(self.pidfd, select.POLLIN) + if not poller.poll(max(0, int(timeout * 1000))): + raise TimeoutError(f"session pid={self.pid} timed out") + decoded = Sys.pidfd_get_info(self.pidfd).decoded_exit + if decoded is None: + raise RuntimeError(f"missing exit code on pidfd {self.pidfd}") + self._cached_exit = decoded + return decoded + + def close(self) -> None: + self.pidfd = Sys.close_fd(self.pidfd) + + +class NsExec: + fd: int + + def __init__( + self, + flags: NsExecFlag | int = NsExecFlag.DEFAULT, + *, + fd: int | None = None, + ) -> None: + self.fd = ( + fd + if fd is not None + else Sys.syscall("nsexec_open", ctypes.c_uint(int(flags))) + ) + + @classmethod + def from_fd(cls, fd: int) -> NsExec: + return cls(fd=fd) + + def dup(self) -> NsExec: + return NsExec.from_fd(os.dup(self.fd)) + + def send(self, sock: socket.socket) -> None: + socket.send_fds(sock, [b"U"], [self.fd]) + + @classmethod + def recv(cls, sock: socket.socket, timeout: float = 5.0) -> NsExec: + ready, _, _ = select.select([sock], [], [], timeout) + if not ready: + raise TimeoutError("timed out receiving nsexec fd") + _, fds, _, _ = socket.recv_fds(sock, 1, 1) + if not fds: + raise RuntimeError("socket closed without nsexec fd") + return cls.from_fd(fds[0]) + + def fileno(self) -> int: + return self.fd + + def __enter__(self) -> NsExec: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + self.fd = Sys.close_fd(self.fd) + + def get_nsfd(self, nstype: CloneFlag | int) -> int: + return Sys.ioctl(self.fd, Ioctl.NSEXEC_GET_NSFD, int(nstype)) + + def share_nsfd(self, nsfd: int) -> None: + Sys.ioctl(self.fd, Ioctl.NSEXEC_SHARE_NSFD, nsfd) + + def set_idmap( + self, + uid_extents: Sequence[tuple[int, int, int]] = (), + gid_extents: Sequence[tuple[int, int, int]] = (), + projid_extents: Sequence[tuple[int, int, int]] = (), + *, + flags: UsernsFlag | int = UsernsFlag.NONE, + ) -> None: + ufd = self.get_nsfd(CloneFlag.NEWUSER) + try: + Sys.set_userns_idmap( + ufd, + uid_extents=uid_extents, + gid_extents=gid_extents, + projid_extents=projid_extents, + flags=flags, + ) + finally: + os.close(ufd) + + def map_self(self) -> None: + self.set_idmap( + uid_extents=((0, os.geteuid(), 1),), + gid_extents=((0, os.getegid(), 1),), + ) + + def wait(self, flags: int = 0) -> WaitResult: + res = os.waitid(int(WaitIdType.NSEXEC), self.fd, os.WEXITED | flags) + if res is None: + return WaitResult(pid=0) + return WaitResult( + pid=int(res.si_pid), + status=int(res.si_status), + code=int(res.si_code), + uid=int(res.si_uid), + ) + + def poll_dead(self, timeout_ms: int = 0) -> bool: + poller = select.poll() + poller.register(self.fd, select.POLLIN) + return any(ev & select.POLLHUP for _, ev in poller.poll(timeout_ms)) + + def kill(self, sig: signal.Signals | int) -> None: + Sys.pidfd_send_signal(self.fd, int(sig)) + + def clone_into( + self, + extra_flags: CloneFlag | int = CloneFlag.NONE, + exit_signal: int = int(signal.SIGCHLD), + *, + size: int | None = None, + cgroup_fd: int = -1, + ) -> tuple[int, int]: + pidfd_box = ctypes.c_int(-1) + args = CloneArgs() + args.flags = int(CloneFlag.INTO_NSEXEC) | int(extra_flags) + args.exit_signal = exit_signal + args.nsexec = self.fd & 0xFFFFFFFFFFFFFFFF + if int(extra_flags) & int(CloneFlag.PIDFD): + args.pidfd = ctypes.addressof(pidfd_box) + if cgroup_fd >= 0: + args.cgroup = cgroup_fd & 0xFFFFFFFFFFFFFFFF + pid = Sys.clone3(args, size=size) + return pid, int(pidfd_box.value) + + def spawn_fn( + self, + fn: Callable[[], int | None], + extra_flags: CloneFlag = CloneFlag.NONE, + *, + exit_signal: int | None = None, + ) -> tuple[int, int]: + sig = ( + (0 if extra_flags & CloneFlag.AUTOREAP else int(signal.SIGCHLD)) + if exit_signal is None + else exit_signal + ) + pid, pidfd = self.clone_into(extra_flags=extra_flags, exit_signal=sig) + if pid == 0: + try: + self.close() + rc = fn() + os._exit(0 if rc is None else int(rc)) + except BaseException: + os._exit(126) + return pid, pidfd + + def make_mount( + self, + fstype: str, + attr_flags: MountAttrFlag = MountAttrFlag.NONE, + options: Mapping[str, str | None] | None = None, + ) -> int: + fsfd = Sys.fsopen(fstype) + try: + Sys.fsconfig(fsfd, FsconfigCmd.SET_NSEXEC, aux=self.fd) + if options: + for k, v in options.items(): + if v is None: + Sys.fsconfig(fsfd, FsconfigCmd.SET_FLAG, key=k) + else: + Sys.fsconfig( + fsfd, FsconfigCmd.SET_STRING, key=k, value=str(v) + ) + Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE) + return Sys.fsmount(fsfd, attr_flags=attr_flags) + finally: + os.close(fsfd) + + +@dataclass +class Cell: + """Sandbox cell managed directly from host space without helper forks.""" + + name: str + flags: NsExecFlag = NsExecFlag.DEFAULT + ul: NsExec = field(init=False) + mntns_fd: int = field(init=False, default=-1) + root_dfd: int = field(init=False, default=-1) + init_pid: int = field(init=False, default=0) + init_pidfd: int = field(init=False, default=-1) + _ctrl_wfd: int = field(init=False, default=-1, repr=False) + + def __post_init__(self) -> None: + self.ul = NsExec(self.flags) + try: + self.mntns_fd = self.ul.get_nsfd(CloneFlag.NEWNS) + except Exception: + self.ul.close() + raise + + @classmethod + def from_fds( + cls, name: str, ul_fd: int, mntns_fd: int, root_dfd: int = -1 + ) -> Cell: + obj = cls.__new__(cls) + obj.name = name + obj.flags = NsExecFlag.DEFAULT + obj.ul = NsExec.from_fd(ul_fd) + obj.mntns_fd = mntns_fd + obj.root_dfd = root_dfd + obj.init_pid = 0 + obj.init_pidfd = -1 + obj._ctrl_wfd = -1 + return obj + + def send(self, sock: socket.socket) -> None: + fds = [self.ul.fd, self.mntns_fd] + if self.root_dfd >= 0: + fds.append(self.root_dfd) + socket.send_fds(sock, [b"C"], fds) + + @classmethod + def recv( + cls, name: str, sock: socket.socket, timeout: float = 5.0 + ) -> Cell: + ready, _, _ = select.select([sock], [], [], timeout) + if not ready: + raise TimeoutError("timed out receiving cell") + _, fds, _, _ = socket.recv_fds(sock, 2, 3) + if len(fds) < 2: + for fd in fds: + Sys.close_fd(fd) + raise RuntimeError("incomplete cell fd handoff") + return cls.from_fds( + name, fds[0], fds[1], fds[2] if len(fds) > 2 else -1 + ) + + def __enter__(self) -> Cell: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() + + def share_from( + self, + other: Cell | NsExec, + nstypes: Sequence[CloneFlag] = (CloneFlag.NEWNET, CloneFlag.NEWIPC), + ) -> None: + src = other.ul if isinstance(other, Cell) else other + for nstype in nstypes: + try: + nsfd = src.get_nsfd(nstype) + except OSError as exc: + if ( + nstype == CloneFlag.NEWTIME + and exc.errno == errno.EOPNOTSUPP + ): + continue + raise + try: + self.ul.share_nsfd(nsfd) + finally: + os.close(nsfd) + + def share_host( + self, nstypes: Sequence[CloneFlag] = (CloneFlag.NEWNET,) + ) -> None: + for nstype in nstypes: + path = f"/proc/self/ns/{NS_NAMES[nstype]}" + if not os.path.exists(path): + continue + nsfd = os.open(path, os.O_RDONLY | os.O_CLOEXEC) + try: + self.ul.share_nsfd(nsfd) + finally: + os.close(nsfd) + + def _move_to_mntns( + self, mfd: int, target: str, *, beneath: bool = False + ) -> None: + flags = MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS + if beneath: + flags |= MoveMountFlag.BENEATH + Sys.move_mount(mfd, "", self.mntns_fd, target, flags) + + def _setup_devfs(self) -> None: + dev_nodes = [ + n + for n in DEV_NODES + if os.path.exists(f"/dev/{n}") + and not os.path.islink(f"/dev/{n}") + and not os.path.isdir(f"/dev/{n}") + ] + dev_fd = self.ul.make_mount( + "tmpfs", + attr_flags=MountAttrFlag.NOSUID | MountAttrFlag.NOEXEC, + options={"mode": "0755"}, + ) + try: + for sub in ("pts", "shm", "mqueue"): + os.mkdir(sub, 0o755, dir_fd=dev_fd) + for node in dev_nodes: + os.close( + os.open( + node, + os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC, + 0o666, + dir_fd=dev_fd, + ) + ) + os.symlink("/proc/self/fd", "fd", dir_fd=dev_fd) + os.symlink("/proc/self/fd/0", "stdin", dir_fd=dev_fd) + os.symlink("/proc/self/fd/1", "stdout", dir_fd=dev_fd) + os.symlink("/proc/self/fd/2", "stderr", dir_fd=dev_fd) + os.symlink("pts/ptmx", "ptmx", dir_fd=dev_fd) + self._move_to_mntns(dev_fd, "dev") + finally: + os.close(dev_fd) + + for node in dev_nodes: + self.bind_mount(f"/dev/{node}", f"dev/{node}") + self.mount_fs( + "tmpfs", + "dev/shm", + attr_flags=MountAttrFlag.NOSUID | MountAttrFlag.NODEV, + ) + for fstype, target, attr_flags, opts in ( + ( + "devpts", + "dev/pts", + MountAttrFlag.NOSUID | MountAttrFlag.NOEXEC, + {"ptmxmode": "0666", "mode": "0620"}, + ), + ( + "mqueue", + "dev/mqueue", + ( + MountAttrFlag.NOSUID + | MountAttrFlag.NODEV + | MountAttrFlag.NOEXEC + ), + None, + ), + ): + try: + self.mount_fs( + fstype, target, attr_flags=attr_flags, options=opts + ) + except OSError as exc: + if exc.errno not in (errno.ENODEV, errno.EPERM): + raise + + def setup_rootfs( + self, + *, + dirs: Sequence[str] = ("proc", "tmp", "mnt"), + procfs: bool = True, + devfs: bool = False, + ro_root: bool = False, + host_runtime: bool = False, + map_self: bool = True, + ) -> None: + if map_self: + self.ul.map_self() + + wanted = list(dirs) + for extra in (("dev",) if devfs else ()) + ( + ("tmp", "run") if ro_root else () + ): + if extra not in wanted: + wanted.append(extra) + + fsfd = Sys.fsopen("tmpfs") + rootfd = -1 + binds: list[str] = [] + try: + Sys.fsconfig(fsfd, FsconfigCmd.SET_NSEXEC, aux=self.ul.fd) + Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE) + attrs = ( + MountAttrFlag.NOSUID | MountAttrFlag.NODEV + if ro_root + else MountAttrFlag.NONE + ) + rootfd = Sys.fsmount(fsfd, attr_flags=attrs) + for d in wanted: + os.mkdir(d, 0o755, dir_fd=rootfd) + if host_runtime: + for entry in HOST_RUNTIME_DIRS: + src = f"/{entry}" + if os.path.islink(src): + os.symlink(os.readlink(src), entry, dir_fd=rootfd) + elif os.path.isdir(src): + if entry not in wanted: + os.mkdir(entry, 0o755, dir_fd=rootfd) + binds.append(entry) + if ro_root: + Sys.fsconfig(fsfd, FsconfigCmd.SET_FLAG, key="ro") + Sys.fsconfig(fsfd, FsconfigCmd.CMD_RECONFIGURE) + self._move_to_mntns(rootfd, "/") + except Exception: + Sys.close_fd(rootfd) + raise + finally: + os.close(fsfd) + + self.root_dfd = rootfd + for entry in binds: + self.bind_mount(f"/{entry}", entry) + if ro_root: + for rw in ("tmp", "run"): + self.mount_fs( + "tmpfs", + rw, + attr_flags=MountAttrFlag.NOSUID | MountAttrFlag.NODEV, + ) + if procfs and "proc" in wanted: + self.mount_fs( + "proc", + "proc", + attr_flags=( + MountAttrFlag.NOSUID + | MountAttrFlag.NODEV + | MountAttrFlag.NOEXEC + ), + ) + if devfs: + self._setup_devfs() + + def mount_fs( + self, + fstype: str, + target: str, + *, + attr_flags: MountAttrFlag = MountAttrFlag.NONE, + options: Mapping[str, str | None] | None = None, + beneath: bool = False, + ) -> None: + mfd = self.ul.make_mount( + fstype, attr_flags=attr_flags, options=options + ) + try: + self._move_to_mntns(mfd, target.lstrip("/"), beneath=beneath) + finally: + os.close(mfd) + + def bind_mount( + self, host_src: str, target: str, *, beneath: bool = False + ) -> None: + flags = MoveMountFlag.T_MNTNS | MoveMountFlag.CLONE + if beneath: + flags |= MoveMountFlag.BENEATH + Sys.move_mount( + Sys.AT_FDCWD, host_src, self.mntns_fd, target.lstrip("/"), flags + ) + + def boot(self, timeout: float = 5.0) -> int: + ready_r, ready_w = os.pipe2(os.O_CLOEXEC) + ctrl_r, ctrl_w = os.pipe2(os.O_CLOEXEC) + try: + + def supervisor() -> int: + low = 3 + for keep_fd in sorted({ready_w, ctrl_r}): + if keep_fd > low: + os.closerange(low, keep_fd) + low = keep_fd + 1 + os.closerange(low, 0x7FFFFFFF) + Sys.prctl(PrctlOp.SET_DUMPABLE, 1) + + def reap(_s: int, _f: Any) -> None: + while True: + try: + if os.waitpid(-1, os.WNOHANG)[0] <= 0: + break + except ChildProcessError: + break + + signal.signal(signal.SIGCHLD, reap) + signal.signal(signal.SIGTERM, lambda _s, _f: os._exit(0)) + if os.getpid() != 1: + os._exit(125) + os.write(ready_w, b"R") + os.close(ready_w) + while True: + try: + cmd = os.read(ctrl_r, 1) + except InterruptedError: + continue + break + os.close(ctrl_r) + return cmd[0] if cmd else 0 + + pid, pidfd = self.ul.spawn_fn( + supervisor, + extra_flags=( + CloneFlag.PIDFD + | CloneFlag.AUTOREAP + | CloneFlag.CLEAR_SIGHAND + ), + ) + except Exception: + for fd in (ready_r, ready_w, ctrl_r, ctrl_w): + Sys.close_fd(fd) + raise + + os.close(ready_w) + os.close(ctrl_r) + try: + poller = select.poll() + poller.register(ready_r, select.POLLIN) + if not poller.poll(max(0, int(timeout * 1000))) or ( + os.read(ready_r, 1) != b"R" + ): + raise RuntimeError("cell PID 1 failed startup") + except Exception: + Sys.close_fd(ctrl_w) + Sys.close_fd(pidfd) + with suppress(OSError): + self.ul.kill(signal.SIGKILL) + raise + finally: + os.close(ready_r) + + self.init_pid = pid + self.init_pidfd = pidfd + self._ctrl_wfd = ctrl_w + return pid + + def shutdown( + self, exit_code: int = 0, *, timeout: float = 5.0 + ) -> WaitResult: + if self._ctrl_wfd >= 0: + with suppress(OSError): + os.write(self._ctrl_wfd, bytes([exit_code & 0xFF])) + self._ctrl_wfd = Sys.close_fd(self._ctrl_wfd) + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + ms = max(0, int((deadline - time.monotonic()) * 1000)) + if self.ul.poll_dead(min(ms, 100)): + return self.wait(nohang=True) + raise TimeoutError(f"cell {self.name!r} shutdown timed out") + + def exec_fn( + self, + fn: Callable[[], int | None], + *, + autokill: bool = False, + nnp: bool = False, + ) -> Session: + flags = CloneFlag.PIDFD | CloneFlag.AUTOREAP | CloneFlag.CLEAR_SIGHAND + if nnp or autokill: + flags |= CloneFlag.NNP + if autokill: + flags |= CloneFlag.PIDFD_AUTOKILL + + def entry() -> int: + self._ctrl_wfd = Sys.close_fd(self._ctrl_wfd) + self.init_pidfd = Sys.close_fd(self.init_pidfd) + self.root_dfd = Sys.close_fd(self.root_dfd) + self.mntns_fd = Sys.close_fd(self.mntns_fd) + rc = fn() + return 0 if rc is None else int(rc) + + pid, pidfd = self.ul.spawn_fn(entry, extra_flags=flags) + return Session(pid=pid, pidfd=pidfd, autokill=autokill) + + def exec_argv( + self, + argv: Sequence[str], + env: Mapping[str, str] | None = None, + *, + autokill: bool = False, + ) -> Session: + bin_fd = -1 + if self.root_dfd >= 0: + bin_fd = Sys.openat2( + self.root_dfd, + argv[0], + os.O_RDONLY | os.O_CLOEXEC, + resolve=ResolveFlag.IN_ROOT, + ) + flags = ( + CloneFlag.PIDFD + | CloneFlag.AUTOREAP + | CloneFlag.CLEAR_SIGHAND + | CloneFlag.VFORK + ) + if autokill: + flags |= CloneFlag.NNP | CloneFlag.PIDFD_AUTOKILL + try: + pid, pidfd = self.ul.clone_into(extra_flags=flags, exit_signal=0) + if pid == 0: + try: + self.close() + if bin_fd >= 0: + Sys.execveat(bin_fd, "", argv, env, AtFlag.EMPTY_PATH) + if env is None: + os.execv(argv[0], list(argv)) + os.execve(argv[0], list(argv), dict(env)) + except BaseException: + os._exit(127) + return Session(pid=pid, pidfd=pidfd, autokill=autokill) + finally: + Sys.close_fd(bin_fd) + + def kill(self, sig: signal.Signals | int = signal.SIGTERM) -> None: + self.ul.kill(sig) + + def wait(self, nohang: bool = False) -> WaitResult: + return self.ul.wait(os.WNOHANG if nohang else 0) + + def close(self) -> None: + self._ctrl_wfd = Sys.close_fd(self._ctrl_wfd) + self.init_pidfd = Sys.close_fd(self.init_pidfd) + self.root_dfd = Sys.close_fd(self.root_dfd) + self.mntns_fd = Sys.close_fd(self.mntns_fd) + self.ul.close() + + +class EventKind(StrEnum): + CELL = "cell" + SESSION = "session" + + +@dataclass(frozen=True) +class CellEvent: + kind: EventKind + name: str + pid: int + exit_code: int | None + +class CellManager: + """Single-loop epoll multiplexer for Cells and Sessions.""" + + def __init__(self) -> None: + self._epoll = select.epoll() + self._cells: dict[int, Cell] = {} + self._sessions: dict[int, tuple[str, Session]] = {} + + def __enter__(self) -> CellManager: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() + + def register_cell(self, cell: Cell) -> None: + fd = cell.ul.fd + self._epoll.register(fd, select.EPOLLIN | select.EPOLLEXCLUSIVE) + self._cells[fd] = cell + + def register_session(self, name: str, session: Session) -> None: + fd = session.pidfd + self._epoll.register(fd, select.EPOLLIN) + self._sessions[fd] = (name, session) + + def poll_events(self, timeout: float = 0.0) -> list[CellEvent]: + out: list[CellEvent] = [] + for fd, ev in self._epoll.poll(timeout): + if fd in self._cells and (ev & select.EPOLLHUP): + cell = self._cells.pop(fd) + with suppress(OSError): + self._epoll.unregister(fd) + res = cell.wait(nohang=True) + out.append( + CellEvent( + EventKind.CELL, cell.name, res.pid, res.exit_code + ) + ) + elif fd in self._sessions and (ev & select.EPOLLIN): + name, sess = self._sessions.pop(fd) + with suppress(OSError): + self._epoll.unregister(fd) + code = sess.wait(timeout=1.0) + sess.close() + out.append(CellEvent(EventKind.SESSION, name, sess.pid, code)) + return out + + def close(self) -> None: + for _, sess in list(self._sessions.values()): + sess.close() + self._sessions.clear() + for cell in list(self._cells.values()): + cell.close() + self._cells.clear() + self._epoll.close() diff --git a/tools/testing/selftests/nsexec/config b/tools/testing/selftests/nsexec/config new file mode 100644 index 000000000000..29ae7a268560 --- /dev/null +++ b/tools/testing/selftests/nsexec/config @@ -0,0 +1,13 @@ +CONFIG_CGROUPS=y +CONFIG_IPC_NS=y +CONFIG_NET_NS=y +CONFIG_NSEXEC=y +CONFIG_PID_NS=y +CONFIG_POSIX_MQUEUE=y +CONFIG_PROC_FS=y +CONFIG_SECURITY=y +CONFIG_SECURITY_LANDLOCK=y +CONFIG_TIME_NS=y +CONFIG_TMPFS=y +CONFIG_USER_NS=y +CONFIG_UTS_NS=y diff --git a/tools/testing/selftests/nsexec/machine.py b/tools/testing/selftests/nsexec/machine.py new file mode 100644 index 000000000000..c08d5fe9143f --- /dev/null +++ b/tools/testing/selftests/nsexec/machine.py @@ -0,0 +1,333 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Copyright (C) 2026 Opinsys Oy + +"""Choice-tape state-machine engine with deterministic shrinking. + +Every case is a pure function of (seed, scenario, case index): the case +seed drives the choice tape, and shrinking is bounded by attempt count +only, so re-running the same coordinates replays both the original +failure and its minimal counterexample. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator, Sequence +from dataclasses import dataclass +import hashlib +import os +import random +import struct +from typing import ClassVar, TypeVar + +T = TypeVar("T") + + +class SkipScenario(Exception): + """Raised when a scenario's kernel capability or Kconfig is disabled.""" + + +class _StopTrace(Exception): + pass + + +class ChoiceStream: + def __init__( + self, *, seed: int | None = None, replay: Sequence[int] | None = None + ) -> None: + self._rng = random.Random(seed) if replay is None else None + self._replay = list(replay) if replay is not None else None + self._cursor = 0 + self.recorded: list[int] = [] + self.step_spans: list[tuple[int, int]] = [] + self._step_start: int | None = None + + def begin_step(self) -> None: + self._step_start = len(self.recorded) + + def end_step(self) -> None: + if self._step_start is not None: + self.step_spans.append((self._step_start, len(self.recorded))) + self._step_start = None + + def draw_int(self, lo: int, hi: int) -> int: + span = hi - lo + if self._replay is not None: + if self._cursor >= len(self._replay): + raise _StopTrace() + val = min(self._replay[self._cursor], span) + self._cursor += 1 + else: + assert self._rng is not None + val = self._rng.randint(0, span) if span > 0 else 0 + self.recorded.append(val) + return lo + val + + def draw_bool(self) -> bool: + return self.draw_int(0, 1) == 1 + + def pick(self, items: Sequence[T]) -> T: + return items[self.draw_int(0, len(items) - 1)] + + def weighted(self, rules: Sequence[tuple[int, T]]) -> T: + point = self.draw_int(0, sum(w for w, _ in rules) - 1) + acc = 0 + for weight, item in rules: + acc += weight + if point < acc: + return item + return rules[-1][1] + + +@dataclass(frozen=True) +class RunConfig: + seed: int + cases: int + steps: int | None = None + case: int | None = None + + +@dataclass(frozen=True) +class Failure: + scenario: str + case_name: str + reason: str + trace: tuple[str, ...] + case_index: int + + def format_report(self, *, seed: int, cmd: str) -> str: + target = ( + f"{self.scenario}.{self.case_name}" + if self.case_name + else self.scenario + ) + lines = [ + f"scenario {target} failed (case {self.case_index}):", + f" reason: {self.reason}", + ] + if self.trace: + lines.append(" steps:") + lines.extend(f" {line}" for line in self.trace) + lines.append( + f" replay: NSEXEC_SEED=0x{seed:016x} " + f"NSEXEC_CASE={self.case_index} {cmd} {self.scenario}" + ) + return "\n".join(lines) + + +@dataclass(frozen=True) +class CaseResult: + name: str + failure: Failure | None = None + + +class ScenarioMachine: + STEPS: ClassVar[int] = 20 + + def __init__(self) -> None: + self.trace: list[str] = [] + self.words: list[str] = [] + self._step_no = 0 + self._step_word = "" + + def word(self, token: str) -> None: + self._step_word = token + + def note(self, msg: str) -> None: + self.trace.append(f"[{self._step_no:02d}] {msg}") + + def run_step(self, tc: ChoiceStream) -> None: + self._step_no += 1 + self._step_word = "" + try: + self.step(tc) + finally: + if self._step_word: + self.words.append(self._step_word) + def step(self, tc: ChoiceStream) -> None: + raise NotImplementedError + + def check_invariants(self) -> None: + pass + + def close(self) -> None: + pass + + +class Machine: + SHRINK_ATTEMPTS: ClassVar[int] = 48 + + @staticmethod + def parse_seed(raw: str) -> int: + val = int(raw.strip(), 0) + if val < 0 or val > 0xFFFFFFFFFFFFFFFF: + raise ValueError("seed must be an unsigned 64-bit integer") + return val + + @staticmethod + def generate_seed() -> int: + return int.from_bytes(os.urandom(8), "big") + + @staticmethod + def _case_seed(seed: int, name: str, idx: int) -> int: + h = hashlib.blake2b(digest_size=8) + h.update(struct.pack(">QQ", seed & 0xFFFFFFFFFFFFFFFF, idx)) + h.update(name.encode("utf-8")) + return int.from_bytes(h.digest(), "big") + + @staticmethod + def _open_fd_count() -> int | None: + try: + return len(os.listdir("/proc/self/fd")) + except OSError: + return None + + @classmethod + def _exec_trace( + cls, + factory: Callable[[], ScenarioMachine], + tc: ChoiceStream, + steps: int, + ) -> tuple[str | None, list[str], str]: + fds_before = cls._open_fd_count() + machine = factory() + reason: str | None = None + try: + machine.check_invariants() + for _ in range(steps): + tc.begin_step() + try: + machine.run_step(tc) + machine.check_invariants() + except _StopTrace: + break + finally: + tc.end_step() + except SkipScenario: + raise + except AssertionError as exc: + reason = str(exc) or "assertion failed" + except Exception as exc: + reason = f"{type(exc).__name__}: {exc}" + finally: + trace = list(machine.trace) + case_name = "_".join(machine.words) + machine.close() + if reason is None and fds_before is not None: + fds_after = cls._open_fd_count() + if fds_after is not None and fds_after > fds_before: + reason = f"leaked {fds_after - fds_before} fd(s)" + return reason, trace, case_name + + @classmethod + def _shrink( + cls, + factory: Callable[[], ScenarioMachine], + tc: ChoiceStream, + reason: str, + trace: list[str], + case_name: str, + steps: int, + ) -> tuple[str, list[str], str]: + """Minimise a failing tape by deleting steps, then lowering choices. + + Bounded by attempt count rather than wall-clock time so that the + result is a function of the failing case alone. + """ + recorded = list(tc.recorded) + spans = list(tc.step_spans) + attempts = 0 + + def accept(cand: list[int]) -> bool: + nonlocal attempts, recorded, spans, reason, trace, case_name + if attempts >= cls.SHRINK_ATTEMPTS or not cand: + return False + attempts += 1 + ctc = ChoiceStream(replay=cand) + c_reason, c_trace, c_name = cls._exec_trace(factory, ctc, steps) + if c_reason is None: + return False + recorded = list(ctc.recorded) + spans = list(ctc.step_spans) + reason, trace, case_name = c_reason, c_trace, c_name + return True + + chunk = max(1, len(spans) // 2) + while chunk >= 1 and attempts < cls.SHRINK_ATTEMPTS: + idx = len(spans) - chunk + moved = False + while idx >= 0 and len(spans) > 1: + if attempts >= cls.SHRINK_ATTEMPTS: + break + lo, hi = spans[idx][0], spans[idx + chunk - 1][1] + if accept(recorded[:lo] + recorded[hi:]): + moved = True + idx = min(idx, len(spans) - chunk) + else: + idx -= 1 + if not moved: + chunk //= 2 + + pos = 0 + while pos < len(recorded) and attempts < cls.SHRINK_ATTEMPTS: + cur = recorded[pos] + if cur > 0: + c0 = list(recorded) + c0[pos] = 0 + if not accept(c0) and cur > 1: + ch = list(recorded) + ch[pos] = cur // 2 + accept(ch) + pos += 1 + + return reason, trace, case_name + + @classmethod + def iter_cases( + cls, + scenario: str, + machine_cls: type[ScenarioMachine], + config: RunConfig, + *, + progress: Callable[[str], None] | None = None, + ) -> Iterator[CaseResult]: + steps = machine_cls.STEPS if config.steps is None else config.steps + indices = ( + range(config.cases) if config.case is None else (config.case,) + ) + shrunk_once = False + for idx in indices: + if progress is not None: + progress(f"case {idx}") + tc = ChoiceStream(seed=cls._case_seed(config.seed, scenario, idx)) + reason, trace, case_name = cls._exec_trace(machine_cls, tc, steps) + if reason is None: + yield CaseResult(case_name) + continue + if not shrunk_once: + shrunk_once = True + if progress is not None: + progress("shrinking") + reason, trace, case_name = cls._shrink( + machine_cls, tc, reason, trace, case_name, steps + ) + yield CaseResult( + case_name, + Failure(scenario, case_name, reason, tuple(trace), idx), + ) + + @classmethod + def run( + cls, + scenario: str, + machine_cls: type[ScenarioMachine], + config: RunConfig, + *, + progress: Callable[[str], None] | None = None, + ) -> Failure | None: + for res in cls.iter_cases( + scenario, machine_cls, config, progress=progress + ): + if res.failure is not None: + return res.failure + return None diff --git a/tools/testing/selftests/nsexec/oracle.py b/tools/testing/selftests/nsexec/oracle.py new file mode 100644 index 000000000000..ab643bfaff00 --- /dev/null +++ b/tools/testing/selftests/nsexec/oracle.py @@ -0,0 +1,386 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Copyright (C) 2026 Opinsys Oy + +"""Reference shadow state and uAPI decision oracle for nsexec(2).""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from enum import Enum, auto +import errno +import os +from typing import Final + +from cells import ( + CloneArgs, + CloneFlag, + SHAREABLE_NSTYPES, + NsExecFlag, + UsernsFlag, + UsernsIdmap, +) + +PAGE_SIZE: Final[int] = int(os.sysconf("SC_PAGE_SIZE")) + +GET_NSFD_TYPES: Final[frozenset[int]] = frozenset( + int(f) + for f in ( + CloneFlag.NEWNS, + CloneFlag.NEWCGROUP, + CloneFlag.NEWUTS, + CloneFlag.NEWIPC, + CloneFlag.NEWUSER, + CloneFlag.NEWPID, + CloneFlag.NEWNET, + CloneFlag.NEWTIME, + ) +) + +SHARE_NSFD_TYPES: Final[frozenset[int]] = frozenset( + int(f) for f in SHAREABLE_NSTYPES +) + +NSEXEC_MOUNT_FS: Final[frozenset[str]] = frozenset( + ("tmpfs", "ramfs", "proc", "devpts", "mqueue") +) + +ALLOWED_CLONE_EXTRA: Final[int] = int( + CloneFlag.VFORK + | CloneFlag.PIDFD + | CloneFlag.CLEAR_SIGHAND + | CloneFlag.INTO_CGROUP + | CloneFlag.AUTOREAP + | CloneFlag.NNP + | CloneFlag.PIDFD_AUTOKILL +) + + +class State(Enum): + INIT = auto() + RUNNING = auto() + DEAD = auto() + + +class FdKind(Enum): + NSEXEC = auto() + CLOSED = auto() + NS_USER = auto() + NS_MNT = auto() + NS_SHAREABLE = auto() + NS_PID = auto() + OTHER = auto() + + +@dataclass(frozen=True) +class Actor: + owner: bool = True + ancestor_pidns: bool = True + pidns_alive: bool = True + unpriv: bool = False + can_allow_setgroups: bool = False + parent_setid: bool = False + parent_setfcap: bool = True + landlock_mask: int | None = None + + +@dataclass +class UnitModel: + state: State = State.INIT + autokill: bool = True + uid_mapped: bool = False + gid_mapped: bool = False + projid_mapped: bool = False + has_root: bool = False + has_dirs: bool = False + shared_host_mask: int = 0 + foreign_shared_ns: bool = False + mount_depth: dict[str, int] = field( + default_factory=lambda: {"mnt": 0, "tmp": 0, "proc": 0} + ) + + +class Oracle: + """Predicts exact kernel errno (or None for success) from model state.""" + + @staticmethod + def open(actor: Actor, flags: int, active_ns_mask: int) -> int | None: + if flags & ~int(NsExecFlag.ALL): + return errno.EINVAL + if actor.landlock_mask is not None and ( + active_ns_mask & ~actor.landlock_mask + ): + return errno.EPERM + return None + + @staticmethod + def get_nsfd( + actor: Actor, + unit: UnitModel, + fd_kind: FdKind, + nstype: int, + *, + has_timens: bool, + ) -> int | None: + if fd_kind == FdKind.CLOSED: + return errno.EBADF + if fd_kind != FdKind.NSEXEC: + return errno.ENOTTY + if nstype < 0 or nstype > 0xFFFFFFFF: + return errno.EINVAL + if not actor.owner: + return errno.EPERM + if nstype == int(CloneFlag.NEWPID): + if not actor.ancestor_pidns: + return errno.EXDEV + return None if unit.state == State.RUNNING else errno.ESRCH + if nstype == int(CloneFlag.NEWTIME) and not has_timens: + return errno.EOPNOTSUPP + if nstype not in GET_NSFD_TYPES: + return errno.EINVAL + return None + + @staticmethod + def share_nsfd( + actor: Actor, + unit: UnitModel, + ns_kind: FdKind, + nstype: int, + *, + ns_usable: bool = True, + has_timens: bool = True, + ) -> int | None: + if ns_kind == FdKind.CLOSED: + return errno.EBADF + if ns_kind not in ( + FdKind.NS_USER, + FdKind.NS_MNT, + FdKind.NS_SHAREABLE, + FdKind.NS_PID, + ): + return errno.EINVAL + if nstype == int(CloneFlag.NEWTIME) and not has_timens: + return errno.EOPNOTSUPP + if nstype not in SHARE_NSFD_TYPES: + return errno.EINVAL + if not actor.owner or not ns_usable: + return errno.EPERM + if actor.landlock_mask is not None and not ( + actor.landlock_mask & nstype + ): + return errno.EPERM + if unit.state != State.INIT: + return errno.EBUSY + return None + + @staticmethod + def set_idmap( + actor: Actor, + unit: UnitModel, + fd_kind: FdKind, + *, + opener_capable: bool = True, + maps_host_root: bool = False, + multi_extent: bool = False, + size: int = UsernsIdmap.SIZE_VER0, + flags: int = 0, + reserved: int = 0, + null_map: bool = False, + ptr_mismatch: bool = False, + uid_valid: bool | None = None, + gid_valid: bool | None = None, + projid_valid: bool | None = None, + ) -> int | None: + if flags & ~int(UsernsFlag.SETGROUPS_ALLOWED): + return errno.EINVAL + if fd_kind == FdKind.CLOSED: + return errno.EBADF + if fd_kind != FdKind.NS_USER: + return errno.EINVAL + if null_map or size < UsernsIdmap.SIZE_VER0: + return errno.EINVAL + if size > PAGE_SIZE: + return errno.E2BIG + if reserved or ptr_mismatch: + return errno.EINVAL + if uid_valid is None and gid_valid is None and projid_valid is None: + return errno.EINVAL + if (flags & int(UsernsFlag.SETGROUPS_ALLOWED)) and gid_valid is None: + return errno.EINVAL + if not actor.owner and not opener_capable: + return errno.EPERM + if uid_valid is False or gid_valid is False or projid_valid is False: + return errno.EINVAL + if ( + (uid_valid and unit.uid_mapped) + or (gid_valid and unit.gid_mapped) + or (projid_valid and unit.projid_mapped) + ): + return errno.EPERM + if ( + flags & int(UsernsFlag.SETGROUPS_ALLOWED) + ) and not actor.can_allow_setgroups: + return errno.EPERM + if maps_host_root and not actor.parent_setfcap: + return errno.EPERM + if multi_extent and not actor.parent_setid: + return errno.EPERM + return None + + @staticmethod + def fsconfig_nsexec( + actor: Actor, + aux_kind: FdKind, + fstype: str, + *, + already_bound: bool = False, + ) -> int | None: + if aux_kind == FdKind.CLOSED: + return errno.EBADF + if already_bound: + return errno.EBUSY + if aux_kind != FdKind.NSEXEC: + return errno.EINVAL + if not actor.owner: + return errno.EPERM + if fstype not in NSEXEC_MOUNT_FS: + return errno.EOPNOTSUPP + if fstype == "proc" and not actor.ancestor_pidns: + return errno.EINVAL + return None + + @staticmethod + def move_mount( + actor: Actor, + unit: UnitModel, + *, + src_same_unit: bool = True, + src_nouser: bool = False, + target: str = "/", + t_mntns: bool = True, + clone: bool = False, + beneath: bool = False, + set_group: bool = False, + ) -> int | None: + if clone and not t_mntns: + return errno.EINVAL + if (beneath and set_group) or (t_mntns and set_group): + return errno.EINVAL + if not actor.owner: + return errno.EPERM + if target == "/": + if beneath: + return errno.EINVAL + if unit.has_root: + return errno.EBUSY + return errno.EINVAL if (src_nouser or not src_same_unit) else None + if not unit.has_root: + return errno.ENOENT + if target == ".": + return errno.EINVAL if beneath else errno.EBUSY + if not unit.has_dirs: + return errno.ENOENT + if target == "tmp/..": + return errno.EINVAL if beneath else errno.EBUSY + if beneath and unit.mount_depth.get(target, 0) == 0: + return errno.EINVAL + if src_nouser or not src_same_unit: + return errno.EINVAL + return None + + @staticmethod + def clone_into( + actor: Actor, + unit: UnitModel, + fd_kind: FdKind, + *, + size: int = CloneArgs.SIZE_VER3, + extra_flags: int = 0, + exit_signal: int = 17, + active_ns_mask: int = 0, + ) -> int | None: + if size > PAGE_SIZE: + return errno.E2BIG + if size < CloneArgs.SIZE_VER3: + return errno.EINVAL + if extra_flags & ~ALLOWED_CLONE_EXTRA: + return errno.EINVAL + if exit_signal < 0 or exit_signal > 64: + return errno.EINVAL + if fd_kind == FdKind.CLOSED: + return errno.EBADF + if fd_kind != FdKind.NSEXEC: + return errno.EINVAL + if not actor.owner: + return errno.EPERM + if not actor.ancestor_pidns: + return errno.EXDEV + if not unit.has_root: + return errno.ENOENT + if unit.state == State.DEAD or not actor.pidns_alive: + return errno.ESRCH + if unit.foreign_shared_ns: + return errno.EPERM + if actor.landlock_mask is not None: + required = int( + CloneFlag.NEWUSER | CloneFlag.NEWNS | CloneFlag.NEWPID + ) | (active_ns_mask & ~unit.shared_host_mask) + if required & ~actor.landlock_mask: + return errno.EPERM + if (extra_flags & int(CloneFlag.AUTOREAP)) and exit_signal != 0: + return errno.EINVAL + if extra_flags & int(CloneFlag.PIDFD_AUTOKILL): + need = int(CloneFlag.PIDFD | CloneFlag.AUTOREAP) + if (extra_flags & need) != need: + return errno.EINVAL + if not (extra_flags & int(CloneFlag.NNP)) and actor.unpriv: + return errno.EPERM + return None + + @staticmethod + def send_signal( + actor: Actor, + unit: UnitModel, + fd_kind: FdKind, + *, + sig: int, + has_info: bool = False, + flags: int = 0, + ) -> int | None: + if fd_kind != FdKind.NSEXEC: + return errno.EBADF + if has_info or flags or sig < 0 or sig > 64: + return errno.EINVAL + if not actor.ancestor_pidns: + return errno.EXDEV + if unit.state != State.RUNNING: + return errno.ESRCH + return None + + @staticmethod + def waitid( + actor: Actor, + unit: UnitModel, + fd_kind: FdKind, + *, + neg_fd: bool = False, + options: int = os.WEXITED, + has_rusage: bool = False, + nonblock: bool = False, + ) -> int | None: + if neg_fd or has_rusage: + return errno.EINVAL + if options & ~(os.WEXITED | os.WNOHANG | os.WNOWAIT): + return errno.EINVAL + if not (options & os.WEXITED): + return errno.EINVAL + if fd_kind != FdKind.NSEXEC: + return errno.EBADF + if not actor.ancestor_pidns or unit.state == State.INIT: + return errno.ECHILD + if unit.state == State.RUNNING: + if options & os.WNOHANG: + return None + if nonblock: + return errno.EAGAIN + return None diff --git a/tools/testing/selftests/nsexec/selftest.py b/tools/testing/selftests/nsexec/selftest.py new file mode 100755 index 000000000000..7acf89ff7912 --- /dev/null +++ b/tools/testing/selftests/nsexec/selftest.py @@ -0,0 +1,2887 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0 +# +# Copyright (C) 2026 Opinsys Oy + +"""Parametric model-based selftest suite for nsexec(2) and Cells.""" + +from __future__ import annotations + +import argparse +from collections.abc import Callable, Sequence +from contextlib import ExitStack, suppress +import ctypes +from dataclasses import dataclass, field +import errno +import importlib +import os +from pathlib import Path +import pty +import select +import signal +import socket +import struct +import sys +import tempfile +import time +import traceback +from typing import Any, ClassVar, Final, TypeVar + +from cells import ( + Cell, + CellManager, + CloneArgs, + CloneFlag, + EventKind, + FsconfigCmd, + Ioctl, + MoveMountFlag, + NS_NAMES, + PrctlOp, + SHAREABLE_NSTYPES, + Session, + Sys, + UmountFlag, + NsExec, + NsExecFlag, + UsernsFlag, + UsernsIdmap, + WaitIdType, + WaitResult, +) +from machine import ( + ChoiceStream, + Machine, + RunConfig, + ScenarioMachine, + SkipScenario, +) +from oracle import ( + Actor, + FdKind, + Oracle, + PAGE_SIZE, + State, + UnitModel, +) + +PYTHON_BIN: Final[str] = os.path.realpath(sys.executable or "/proc/self/exe") +SKIP_ERRNOS: Final[tuple[int, ...]] = ( + errno.ENOSYS, + errno.EPERM, + errno.EACCES, + errno.EINVAL, + errno.ENOSPC, +) +PIDFD_NS_IOCTLS: Final[dict[CloneFlag, Ioctl]] = { + CloneFlag.NEWNS: Ioctl.PIDFD_GET_MNT_NAMESPACE, + CloneFlag.NEWCGROUP: Ioctl.PIDFD_GET_CGROUP_NAMESPACE, + CloneFlag.NEWUTS: Ioctl.PIDFD_GET_UTS_NAMESPACE, + CloneFlag.NEWIPC: Ioctl.PIDFD_GET_IPC_NAMESPACE, + CloneFlag.NEWUSER: Ioctl.PIDFD_GET_USER_NAMESPACE, + CloneFlag.NEWPID: Ioctl.PIDFD_GET_PID_NAMESPACE, + CloneFlag.NEWNET: Ioctl.PIDFD_GET_NET_NAMESPACE, + CloneFlag.NEWTIME: Ioctl.PIDFD_GET_TIME_NAMESPACE, +} + + +_T = TypeVar("_T") + + +class NsExecMachine(ScenarioMachine): + @staticmethod + def reap_pid(pid: int) -> int: + _, status = os.waitpid(pid, 0) + return os.waitstatus_to_exitcode(status) + + @staticmethod + def drop_to_uid(uid: int) -> None: + try: + Sys.setgroups_empty() + except OSError as exc: + if exc.errno != errno.EPERM: + raise + os.setresgid(uid, uid, uid) + os.setresuid(uid, uid, uid) + Sys.prctl(PrctlOp.SET_DUMPABLE, 1) + + @staticmethod + def enter_userns_if_unpriv() -> None: + if os.geteuid() == 0: + return + uid, gid = os.geteuid(), os.getegid() + Sys.unshare(CloneFlag.NEWUSER | CloneFlag.NEWNS) + Path("/proc/self/setgroups").write_bytes(b"deny\n") + Path("/proc/self/uid_map").write_bytes(f"0 {uid} 1\n".encode("ascii")) + Path("/proc/self/gid_map").write_bytes(f"0 {gid} 1\n".encode("ascii")) + + @classmethod + def run_isolated(cls, fn: Callable[[], object]) -> None: + r_fd, w_fd = os.pipe2(os.O_CLOEXEC) + pid = Sys.fork() + if pid == 0: + os.close(r_fd) + try: + fn() + except SkipScenario as exc: + os.write(w_fd, f"SKIP:{exc}".encode("utf-8", errors="replace")) + os.close(w_fd) + os._exit(0) + except BaseException as exc: + msg = ( + str(exc) + if isinstance(exc, AssertionError) + else traceback.format_exc() + ) + os.write(w_fd, msg.encode("utf-8", errors="replace")) + os.close(w_fd) + os._exit(1) + os.close(w_fd) + os._exit(0) + os.close(w_fd) + chunks: list[bytes] = [] + while True: + buf = os.read(r_fd, 4096) + if not buf: + break + chunks.append(buf) + os.close(r_fd) + rc = cls.reap_pid(pid) + text = b"".join(chunks).decode("utf-8", errors="replace").strip() + if text.startswith("SKIP:"): + raise SkipScenario(text[5:]) + if text or rc != 0: + raise AssertionError(text or f"isolated child exited {rc}") + + @classmethod + def run_in_foreign_pidns( + cls, ul: NsExec, fn: Callable[[], object] + ) -> None: + def outer() -> None: + ufd = ul.get_nsfd(CloneFlag.NEWUSER) + try: + Sys.setns(ufd, CloneFlag.NEWUSER) + finally: + os.close(ufd) + Sys.unshare(CloneFlag.NEWPID) + cls.run_isolated(fn) + + cls.run_isolated(outer) + + @classmethod + def create_nsexec_as_uid(cls, uid: int) -> NsExec | None: + s_p, s_c = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET) + pid = Sys.fork() + if pid == 0: + s_p.close() + try: + cls.drop_to_uid(uid) + with NsExec() as ul: + ul.send(s_c) + os._exit(0) + except OSError as exc: + os._exit(0 if exc.errno in SKIP_ERRNOS else 1) + finally: + s_c.close() + s_c.close() + got: NsExec | None = None + try: + if select.select([s_p], [], [], 5.0)[0]: + _, fds, _, _ = socket.recv_fds(s_p, 1, 1) + if fds: + got = NsExec.from_fd(fds[0]) + finally: + s_p.close() + if cls.reap_pid(pid) != 0: + if got is not None: + got.close() + raise AssertionError(f"failed creating nsexec as uid {uid}") + return got + + @staticmethod + def check_call( + what: str, exp_errno: int | None, fn: Callable[[], _T] + ) -> _T | None: + try: + res = fn() + except OSError as exc: + if exp_errno is None: + raise AssertionError( + f"{what}: expected success, got {exc}" + ) from exc + if exc.errno != exp_errno: + exp_name = errno.errorcode.get(exp_errno, str(exp_errno)) + got_name = errno.errorcode.get(exc.errno or 0, str(exc.errno)) + raise AssertionError( + f"{what}: expected {exp_name}, got {got_name} ({exc})" + ) from exc + return None + if exp_errno is not None: + exp_name = errno.errorcode.get(exp_errno, str(exp_errno)) + raise AssertionError( + f"{what}: expected {exp_name}, succeeded with {res!r}" + ) + return res + + +@dataclass +class LiveWorker: + pid: int + pidfd: int + ctrl_w: int + autoreap: bool + autokill: bool + + +@dataclass +class LiveUnit: + label: str + model: UnitModel + fds: list[int] + mntns_fd: int + ns_ids: dict[CloneFlag, os.stat_result] + root_dfd: int = -1 + init_pid: int = 0 + init_pidfd: int = -1 + init_ctrl_w: int = -1 + init_autoreap: bool = True + init_reaped: bool = False + expected_wait: WaitResult | None = None + workers: list[LiveWorker] = field(default_factory=list) + + def ul_view(self, idx: int = 0) -> NsExec: + return NsExec.from_fd(self.fds[idx]) + + +class Lifecycle(NsExecMachine): + """Parametric model for nsexec lifecycle, fds, clone, and wait.""" + + STEPS: ClassVar[int] = 24 + MAX_UNITS: ClassVar[int] = 4 + + def __init__(self) -> None: + super().__init__() + self._units: list[LiveUnit] = [] + self._seq = 0 + self._has_timens = os.path.exists("/proc/self/ns/time") + self._unpriv = os.geteuid() != 0 + self._host_ns: dict[CloneFlag, tuple[int, os.stat_result]] = {} + for nstype in SHAREABLE_NSTYPES: + if nstype == CloneFlag.NEWTIME and not self._has_timens: + continue + path = f"/proc/self/ns/{NS_NAMES[nstype]}" + if os.path.exists(path): + fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC) + self._host_ns[nstype] = (fd, os.fstat(fd)) + + def _active_nstypes(self) -> tuple[CloneFlag, ...]: + out = [ + CloneFlag.NEWNS, + CloneFlag.NEWCGROUP, + CloneFlag.NEWUTS, + CloneFlag.NEWIPC, + CloneFlag.NEWUSER, + CloneFlag.NEWNET, + ] + if self._has_timens: + out.append(CloneFlag.NEWTIME) + return tuple(out) + + def _active_mask(self) -> int: + mask = int(CloneFlag.NEWPID) + for nst in self._active_nstypes(): + mask |= int(nst) + return mask + + def _close_harness_fds(self) -> None: + for u in self._units: + for fd in u.fds: + Sys.close_fd(fd) + for w in u.workers: + Sys.close_fd(w.pidfd) + Sys.close_fd(w.ctrl_w) + Sys.close_fd(u.init_pidfd) + Sys.close_fd(u.init_ctrl_w) + Sys.close_fd(u.root_dfd) + Sys.close_fd(u.mntns_fd) + for fd, _ in self._host_ns.values(): + Sys.close_fd(fd) + def _open_units(self) -> list[LiveUnit]: + return [u for u in self._units if u.fds] + + def _ensure_root(self, unit: LiveUnit) -> None: + ul = unit.ul_view() + if not unit.model.uid_mapped or not unit.model.gid_mapped: + u_ext = () if unit.model.uid_mapped else ((0, os.geteuid(), 1),) + g_ext = () if unit.model.gid_mapped else ((0, os.getegid(), 1),) + ul.set_idmap(uid_extents=u_ext, gid_extents=g_ext) + unit.model.uid_mapped = True + unit.model.gid_mapped = True + if not unit.model.has_root: + rfd = ul.make_mount("tmpfs") + try: + for d in ("proc", "tmp", "mnt"): + os.mkdir(d, 0o755, dir_fd=rfd) + Sys.move_mount( + rfd, + "", + unit.mntns_fd, + "/", + MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS, + ) + except Exception: + os.close(rfd) + raise + unit.root_dfd = rfd + unit.model.has_root = True + unit.model.has_dirs = True + + def _sync_death(self, unit: LiveUnit, code: int, status: int) -> None: + for w in unit.workers: + if w.autokill: + w.pidfd = Sys.close_fd(w.pidfd) + else: + w.ctrl_w = Sys.close_fd(w.ctrl_w) + if not w.autoreap and w.pid > 0: + with suppress(ChildProcessError, OSError): + self.reap_pid(w.pid) + w.pid = 0 + w.ctrl_w = Sys.close_fd(w.ctrl_w) + w.pidfd = Sys.close_fd(w.pidfd) + unit.workers.clear() + unit.init_ctrl_w = Sys.close_fd(unit.init_ctrl_w) + + if unit.fds: + if not unit.ul_view().poll_dead(5000): + raise AssertionError(f"{unit.label}: missing POLLHUP on DEAD") + elif unit.init_pidfd >= 0: + poller = select.poll() + poller.register(unit.init_pidfd, select.POLLIN) + if not poller.poll(5000): + raise AssertionError(f"{unit.label}: init pidfd did not exit") + + unit.model.state = State.DEAD + unit.expected_wait = WaitResult( + pid=unit.init_pid, status=status, code=code, uid=os.geteuid() + ) + + def _rule_open(self, tc: ChoiceStream) -> None: + flags = ( + tc.pick((0, 1)) + if len(self._units) < self.MAX_UNITS and tc.draw_int(0, 4) > 0 + else tc.pick((0x2, 0x4, 0x100, 0x80000000)) + ) + exp = Oracle.open(Actor(), flags, self._active_mask()) + self.word("open") + self.note(f"nsexec_open(0x{flags:x}) -> {exp or 'ok'}") + ul = self.check_call("nsexec_open", exp, lambda: NsExec(flags)) + if ul is None: + return + if os.get_inheritable(ul.fd): + raise AssertionError("nsexec_open() missing O_CLOEXEC") + mntns_fd = ul.get_nsfd(CloneFlag.NEWNS) + ns_ids: dict[CloneFlag, os.stat_result] = {} + for nst in self._active_nstypes(): + nfd = ul.get_nsfd(nst) + try: + ns_ids[nst] = os.fstat(nfd) + finally: + os.close(nfd) + label = f"u{self._seq}" + self._seq += 1 + self._units.append( + LiveUnit( + label=label, + model=UnitModel( + autokill=bool(flags & int(NsExecFlag.AUTOKILL)) + ), + fds=[ul.fd], + mntns_fd=mntns_fd, + ns_ids=ns_ids, + ) + ) + + def _rule_dup_or_close(self, tc: ChoiceStream) -> None: + avail = self._open_units() + if not avail: + self._rule_open(tc) + return + unit = tc.pick(avail) + if len(unit.fds) < 3 and tc.draw_bool(): + src = tc.pick(unit.fds) + if tc.draw_bool(): + unit.fds.append(os.dup(src)) + self.word("dup") + self.note(f"{unit.label}: dup -> {len(unit.fds)} fds") + else: + s_a, s_b = socket.socketpair( + socket.AF_UNIX, socket.SOCK_SEQPACKET + ) + try: + NsExec.from_fd(src).send(s_a) + unit.fds.append(NsExec.recv(s_b).fd) + finally: + s_a.close() + s_b.close() + self.word("scm") + self.note(f"{unit.label}: scm_rights -> {len(unit.fds)} fds") + return + + fd = unit.fds.pop(tc.draw_int(0, len(unit.fds) - 1)) + was_running = unit.model.state == State.RUNNING + os.close(fd) + self.word("close") + self.note( + f"{unit.label}: close_fd (rem={len(unit.fds)}, " + f"autokill={unit.model.autokill})" + ) + if not unit.fds and was_running: + if unit.model.autokill: + self._sync_death(unit, os.CLD_KILLED, int(signal.SIGKILL)) + if not unit.init_autoreap and not unit.init_reaped: + if self.reap_pid(unit.init_pid) != -int(signal.SIGKILL): + raise AssertionError("expected -SIGKILL on AUTOKILL") + unit.init_reaped = True + elif unit.init_pidfd >= 0: + poller = select.poll() + poller.register(unit.init_pidfd, select.POLLIN) + if poller.poll(0): + raise AssertionError("init died without AUTOKILL") + + def _rule_get_nsfd(self, tc: ChoiceStream) -> None: + avail = self._open_units() + if not avail: + self._rule_open(tc) + return + unit = tc.pick(avail) + self.word("nsfd") + fd_kind = tc.weighted( + ((8, FdKind.NSEXEC), (1, FdKind.CLOSED), (1, FdKind.NS_MNT)) + ) + nstype = tc.pick( + ( + *(int(f) for f in self._active_nstypes()), + int(CloneFlag.NEWPID), + 0, + int(CloneFlag.VM), + 0x1FFFFFFFF, + ) + ) + foreign_pidns = ( + fd_kind == FdKind.NSEXEC + and nstype == int(CloneFlag.NEWPID) + and tc.draw_int(0, 4) == 0 + ) + actor = Actor(ancestor_pidns=not foreign_pidns) + exp = Oracle.get_nsfd( + actor, + unit.model, + fd_kind, + nstype, + has_timens=self._has_timens, + ) + target_fd = ( + tc.pick(unit.fds) + if fd_kind == FdKind.NSEXEC + else (99999 if fd_kind == FdKind.CLOSED else unit.mntns_fd) + ) + self.note( + f"{unit.label}: get_nsfd(kind={fd_kind.name}, 0x{nstype:x}, " + f"foreign_pidns={foreign_pidns}) -> {exp or 'ok'}" + ) + + def invoke() -> None: + nsfd = self.check_call( + "get_nsfd", + exp, + lambda: Sys.ioctl(target_fd, Ioctl.NSEXEC_GET_NSFD, nstype), + ) + if nsfd is not None: + try: + if Sys.ioctl(nsfd, Ioctl.NS_GET_NSTYPE) != nstype: + raise AssertionError("NS_GET_NSTYPE mismatch") + if not os.path.samestat( + os.fstat(nsfd), unit.ns_ids[CloneFlag(nstype)] + ): + raise AssertionError("nsfd inode mismatch") + finally: + os.close(nsfd) + + if foreign_pidns: + if not unit.model.uid_mapped: + self._ensure_root(unit) + self.run_in_foreign_pidns(unit.ul_view(), invoke) + else: + invoke() + + def _rule_share_nsfd(self, tc: ChoiceStream) -> None: + avail = self._open_units() + if not avail: + self._rule_open(tc) + return + unit = tc.pick(avail) + self.word("share") + ul = unit.ul_view(tc.draw_int(0, len(unit.fds) - 1)) + src_choice = tc.weighted( + ( + (6, "host"), + (4, "peer"), + (2, "unshareable"), + (1, "non_nsfs"), + (1, "closed"), + ) + ) + close_arg = False + src_id: os.stat_result | None = None + from_host = False + + if src_choice == "closed": + ns_kind, nstype, arg_fd = FdKind.CLOSED, 0, 99999 + elif src_choice == "non_nsfs": + ns_kind, nstype, arg_fd = FdKind.NSEXEC, 0, ul.fd + elif src_choice == "unshareable": + flag = tc.pick((CloneFlag.NEWUSER, CloneFlag.NEWNS)) + ns_kind = ( + FdKind.NS_USER if flag == CloneFlag.NEWUSER else FdKind.NS_MNT + ) + nstype = int(flag) + arg_fd = ul.get_nsfd(flag) + close_arg = True + else: + shareable = tuple(self._host_ns.keys()) + flag = tc.pick(shareable) + ns_kind, nstype = FdKind.NS_SHAREABLE, int(flag) + peers = [u for u in avail if u is not unit] + if src_choice == "peer" and peers: + peer = tc.pick(peers) + arg_fd = peer.ul_view().get_nsfd(flag) + src_id = peer.ns_ids[flag] + close_arg = True + else: + arg_fd, src_id = self._host_ns[flag] + from_host = True + + try: + exp = Oracle.share_nsfd( + Actor(), + unit.model, + ns_kind, + nstype, + has_timens=self._has_timens, + ) + self.note( + f"{unit.label}: share_nsfd({src_choice}, 0x{nstype:x}) " + f"in {unit.model.state.name} -> {exp or 'ok'}" + ) + self.check_call("share_nsfd", exp, lambda: ul.share_nsfd(arg_fd)) + if exp is None and src_id is not None: + cflag = CloneFlag(nstype) + unit.ns_ids[cflag] = src_id + if from_host: + unit.model.shared_host_mask |= nstype + else: + unit.model.shared_host_mask &= ~nstype + finally: + if close_arg: + os.close(arg_fd) + + def _spawn_init(self, unit: LiveUnit, autoreap: bool, nnp: bool) -> None: + ul = unit.ul_view() + ready_r, ready_w = os.pipe2(os.O_CLOEXEC) + ctrl_r, ctrl_w = os.pipe2(os.O_CLOEXEC) + flags = CloneFlag.PIDFD | CloneFlag.CLEAR_SIGHAND + if autoreap: + flags |= CloneFlag.AUTOREAP + if nnp: + flags |= CloneFlag.NNP + old_umask = os.umask(0o077) + Sys.prctl(PrctlOp.SET_DUMPABLE, 1) + try: + + def init_fn() -> int: + self._close_harness_fds() + os.close(ready_r) + os.close(ctrl_w) + signal.signal(signal.SIGUSR1, lambda _s, _f: None) + signal.signal(signal.SIGCHLD, lambda _s, _f: None) + cur_umask = os.umask(0o022) + dumpable = Sys.prctl(PrctlOp.GET_DUMPABLE) + nnp_val = Sys.prctl(PrctlOp.GET_NO_NEW_PRIVS) + if ( + os.getpid() != 1 + or cur_umask != 0o077 + or dumpable == 1 + or (nnp and nnp_val != 1) + ): + os._exit(121) + os.write(ready_w, b"I") + os.close(ready_w) + while True: + try: + cmd = os.read(ctrl_r, 1) + except InterruptedError: + continue + break + os.close(ctrl_r) + return cmd[0] if cmd else 0 + + pid, pidfd = ul.spawn_fn(init_fn, extra_flags=flags) + except Exception: + for fd in (ready_r, ready_w, ctrl_r, ctrl_w): + Sys.close_fd(fd) + raise + finally: + os.umask(old_umask) + + os.close(ready_w) + os.close(ctrl_r) + try: + if os.read(ready_r, 1) != b"I": + raise AssertionError(f"{unit.label}: init check failed") + finally: + os.close(ready_r) + + unit.init_pid = pid + unit.init_pidfd = pidfd + unit.init_ctrl_w = ctrl_w + unit.init_autoreap = autoreap + unit.init_reaped = False + unit.model.state = State.RUNNING + + pfd = ul.get_nsfd(CloneFlag.NEWPID) + try: + unit.ns_ids[CloneFlag.NEWPID] = os.fstat(pfd) + finally: + os.close(pfd) + self._check_pidfd_ns( + pidfd, CloneFlag.NEWPID, unit.ns_ids[CloneFlag.NEWPID] + ) + + @staticmethod + def _check_pidfd_ns( + pidfd: int, nst: CloneFlag, expected: os.stat_result + ) -> None: + try: + nfd = Sys.ioctl(pidfd, PIDFD_NS_IOCTLS[nst]) + except OSError as exc: + if os.geteuid() != 0 and exc.errno == errno.EACCES: + return + raise + try: + if not os.path.samestat(os.fstat(nfd), expected): + raise AssertionError(f"{NS_NAMES[nst]} mismatch") + finally: + os.close(nfd) + + def _spawn_worker( + self, unit: LiveUnit, autoreap: bool, autokill: bool, with_setsid: bool + ) -> None: + ul = unit.ul_view() + ready_r, ready_w = os.pipe2(os.O_CLOEXEC) + ctrl_r, ctrl_w = os.pipe2(os.O_CLOEXEC) + flags = CloneFlag.PIDFD | CloneFlag.CLEAR_SIGHAND + if autoreap: + flags |= CloneFlag.AUTOREAP + if autokill: + flags |= CloneFlag.NNP | CloneFlag.PIDFD_AUTOKILL + try: + + def worker_fn() -> int: + self._close_harness_fds() + os.close(ready_r) + os.close(ctrl_w) + signal.signal(signal.SIGUSR1, lambda _s, _f: None) + if os.getpid() <= 1: + os._exit(122) + gc_w = -1 + if with_setsid: + os.setsid() + gc_r, gc_w = os.pipe2(os.O_CLOEXEC) + gc = Sys.fork() + if gc == 0: + os.close(ready_w) + os.close(ctrl_r) + os.close(gc_w) + os.read(gc_r, 1) + os.close(gc_r) + os._exit(0) + os.close(gc_r) + os.write(ready_w, b"W") + os.close(ready_w) + while True: + try: + cmd = os.read(ctrl_r, 1) + except InterruptedError: + continue + break + os.close(ctrl_r) + Sys.close_fd(gc_w) + return cmd[0] if cmd else 0 + + pid, pidfd = ul.spawn_fn(worker_fn, extra_flags=flags) + except Exception: + for fd in (ready_r, ready_w, ctrl_r, ctrl_w): + Sys.close_fd(fd) + raise + + os.close(ready_w) + os.close(ctrl_r) + try: + if os.read(ready_r, 1) != b"W": + raise AssertionError("worker startup failed") + finally: + os.close(ready_r) + + for nst in (CloneFlag.NEWNS, CloneFlag.NEWNET): + self._check_pidfd_ns(pidfd, nst, unit.ns_ids[nst]) + unit.workers.append(LiveWorker(pid, pidfd, ctrl_w, autoreap, autokill)) + + def _rule_clone(self, tc: ChoiceStream) -> None: + avail = self._open_units() + if not avail: + self._rule_open(tc) + return + unit = tc.pick(avail) + self.word("clone") + if ( + unit.model.state == State.INIT + and not unit.model.has_root + and tc.draw_int(0, 2) > 0 + ): + self._ensure_root(unit) + + fd_kind = tc.weighted( + ((10, FdKind.NSEXEC), (1, FdKind.CLOSED), (1, FdKind.NS_MNT)) + ) + size = tc.weighted( + ( + (12, CloneArgs.SIZE_VER3), + (1, CloneArgs.SIZE_VER2), + (1, PAGE_SIZE + 8), + ) + ) + extra = tc.weighted( + ( + (5, int(CloneFlag.PIDFD | CloneFlag.CLEAR_SIGHAND)), + ( + 5, + int( + CloneFlag.PIDFD + | CloneFlag.AUTOREAP + | CloneFlag.CLEAR_SIGHAND + ), + ), + ( + 3, + int( + CloneFlag.PIDFD + | CloneFlag.AUTOREAP + | CloneFlag.NNP + | CloneFlag.PIDFD_AUTOKILL + ), + ), + (1, int(CloneFlag.VM)), + (1, int(CloneFlag.FILES)), + (1, int(CloneFlag.NEWNS)), + (1, int(CloneFlag.NEWPID)), + (1, int(CloneFlag.PARENT)), + (1, int(CloneFlag.PIDFD | CloneFlag.PIDFD_AUTOKILL)), + ) + ) + exit_sig = ( + 0 + if (extra & int(CloneFlag.AUTOREAP)) and tc.draw_int(0, 5) > 0 + else (0 if extra == int(CloneFlag.PARENT) else int(signal.SIGCHLD)) + ) + foreign_pidns = ( + fd_kind == FdKind.NSEXEC + and unit.model.has_root + and tc.draw_int(0, 7) == 0 + ) + actor = Actor(ancestor_pidns=not foreign_pidns, unpriv=self._unpriv) + exp = Oracle.clone_into( + actor, + unit.model, + fd_kind, + size=size, + extra_flags=extra, + exit_signal=exit_sig, + active_ns_mask=self._active_mask(), + ) + + if exp is not None: + target_fd = ( + tc.pick(unit.fds) + if fd_kind == FdKind.NSEXEC + else (99999 if fd_kind == FdKind.CLOSED else unit.mntns_fd) + ) + self.note( + f"{unit.label}: clone_into(kind={fd_kind.name}, sz={size}, " + f"extra=0x{extra:x}, sig={exit_sig}, fpid={foreign_pidns}) " + f"-> {errno.errorcode[exp]}" + ) + buf = ( + ctypes.create_string_buffer(size) if size > PAGE_SIZE else None + ) + + def bad_call() -> None: + if buf is not None: + self.check_call( + "clone3 E2BIG", + exp, + lambda: Sys.syscall( + "clone3", + ctypes.addressof(buf), + ctypes.c_size_t(size), + ), + ) + else: + self.check_call( + "clone_into", + exp, + lambda: NsExec.from_fd(target_fd).clone_into( + extra, exit_signal=exit_sig, size=size + ), + ) + + if foreign_pidns: + self.run_in_foreign_pidns(unit.ul_view(), bad_call) + else: + bad_call() + return + + autoreap = bool(extra & int(CloneFlag.AUTOREAP)) + nnp = bool(extra & int(CloneFlag.NNP)) + autokill = bool(extra & int(CloneFlag.PIDFD_AUTOKILL)) + if unit.model.state == State.INIT: + self._spawn_init(unit, autoreap=autoreap, nnp=nnp) + self.note( + f"{unit.label}: bootstrap PID 1 (autoreap={autoreap}) " + f"-> RUNNING" + ) + elif len(unit.workers) < 3: + setsid = tc.draw_bool() + self._spawn_worker( + unit, + autoreap=autoreap, + autokill=autokill, + with_setsid=setsid, + ) + self.note( + f"{unit.label}: spawn worker #{len(unit.workers)} " + f"(autokill={autokill}, setsid={setsid})" + ) + + def _rule_concurrent_bootstrap(self, tc: ChoiceStream) -> None: + inits = [u for u in self._open_units() if u.model.state == State.INIT] + if not inits: + if len(self._units) >= self.MAX_UNITS: + self._rule_retire_or_exit(tc) + return + self._rule_open(tc) + inits = [ + u for u in self._open_units() if u.model.state == State.INIT + ] + if not inits: + return + unit = tc.pick(inits) + self.word("race") + self._ensure_root(unit) + entrants = tc.draw_int(2, 4) + start_r, start_w = os.pipe2(os.O_CLOEXEC) + rep_r, rep_w = os.pipe2(os.O_CLOEXEC) + ctrl_r, ctrl_w = os.pipe2(os.O_CLOEXEC) + wpids: list[int] = [] + for _ in range(entrants): + wp = Sys.fork() + if wp == 0: + os.close(start_w) + os.close(rep_r) + os.close(ctrl_w) + in_r, in_w = os.pipe2(os.O_CLOEXEC) + os.read(start_r, 1) + os.close(start_r) + + def entrant() -> int: + self._close_harness_fds() + os.close(rep_w) + os.close(in_r) + signal.signal(signal.SIGUSR1, lambda _s, _f: None) + signal.signal(signal.SIGCHLD, lambda _s, _f: None) + mp = os.getpid() + os.write(in_w, bytes([mp])) + os.close(in_w) + if mp != 1: + os.close(ctrl_r) + return 0 + while True: + try: + cmd = os.read(ctrl_r, 1) + except InterruptedError: + continue + break + os.close(ctrl_r) + return cmd[0] if cmd else 0 + + pid, _ = unit.ul_view().spawn_fn( + entrant, + extra_flags=CloneFlag.AUTOREAP | CloneFlag.CLEAR_SIGHAND, + ) + os.close(in_w) + os.close(ctrl_r) + inner_b = os.read(in_r, 1) + os.close(in_r) + if pid > 0 and len(inner_b) == 1: + os.write(rep_w, struct.pack(">BI", inner_b[0], pid)) + os.close(rep_w) + os._exit(0) + os.close(rep_w) + os._exit(1) + wpids.append(wp) + + os.close(start_r) + os.close(rep_w) + os.close(ctrl_r) + os.close(start_w) + seen: set[int] = set() + init_host_pid = 0 + for _ in range(entrants): + rec = os.read(rep_r, 5) + if len(rec) == 5: + mp, hpid = struct.unpack(">BI", rec) + seen.add(mp) + if mp == 1: + init_host_pid = hpid + os.close(rep_r) + for wp in wpids: + if self.reap_pid(wp) != 0: + os.close(ctrl_w) + raise AssertionError("concurrent bootstrap entrant failed") + if seen != set(range(1, entrants + 1)) or init_host_pid <= 0: + os.close(ctrl_w) + raise AssertionError(f"unexpected entrant pids {seen}") + + pfd = unit.ul_view().get_nsfd(CloneFlag.NEWPID) + try: + unit.ns_ids[CloneFlag.NEWPID] = os.fstat(pfd) + finally: + os.close(pfd) + unit.init_pid = init_host_pid + unit.init_pidfd = os.pidfd_open(init_host_pid, 0) + unit.init_ctrl_w = ctrl_w + unit.init_autoreap = True + unit.init_reaped = True + unit.model.state = State.RUNNING + self.note(f"{unit.label}: concurrent_bootstrap({entrants}) -> RUNNING") + + def _rule_retire_or_exit(self, tc: ChoiceStream) -> None: + with_workers = [u for u in self._units if u.workers] + if with_workers and tc.draw_bool(): + unit = tc.pick(with_workers) + w = unit.workers.pop(tc.draw_int(0, len(unit.workers) - 1)) + if w.autokill and tc.draw_bool(): + w.pidfd = Sys.close_fd(w.pidfd) + w.ctrl_w = Sys.close_fd(w.ctrl_w) + self.word("autokill") + self.note(f"{unit.label}: autokill worker closed") + else: + rc = tc.draw_int(0, 50) + os.write(w.ctrl_w, bytes([rc])) + w.ctrl_w = Sys.close_fd(w.ctrl_w) + if not w.autoreap: + if self.reap_pid(w.pid) != rc: + raise AssertionError("worker waitpid mismatch") + elif w.pidfd >= 0: + poller = select.poll() + poller.register(w.pidfd, select.POLLIN) + poller.poll(5000) + if Sys.pidfd_get_info(w.pidfd).decoded_exit != rc: + raise AssertionError("worker pidfd_info mismatch") + w.pidfd = Sys.close_fd(w.pidfd) + self.word("retire") + self.note(f"{unit.label}: worker exited rc={rc}") + return + + running = [ + u for u in self._units if u.model.state == State.RUNNING and u.fds + ] + if not running: + self._rule_clone(tc) + return + unit = tc.pick(running) + self.word("exit") + rc = tc.draw_int(0, 99) + os.write(unit.init_ctrl_w, bytes([rc])) + unit.init_ctrl_w = Sys.close_fd(unit.init_ctrl_w) + self._sync_death(unit, os.CLD_EXITED, rc) + if not unit.init_autoreap and not unit.init_reaped and tc.draw_bool(): + if self.reap_pid(unit.init_pid) != rc: + raise AssertionError("init waitpid mismatch") + unit.init_reaped = True + self.note(f"{unit.label}: init exited rc={rc} -> DEAD") + + def _rule_signal(self, tc: ChoiceStream) -> None: + avail = self._open_units() + if not avail: + self._rule_open(tc) + return + unit = tc.pick(avail) + self.word("signal") + fd_kind = tc.weighted( + ((8, FdKind.NSEXEC), (1, FdKind.CLOSED), (1, FdKind.NS_MNT)) + ) + sig = tc.pick((0, int(signal.SIGUSR1), int(signal.SIGKILL), -1, 9999)) + has_info = tc.draw_int(0, 7) == 0 + flags = 1 if tc.draw_int(0, 7) == 0 else 0 + foreign_pidns = ( + fd_kind == FdKind.NSEXEC + and unit.model.uid_mapped + and tc.draw_int(0, 6) == 0 + ) + actor = Actor(ancestor_pidns=not foreign_pidns) + exp = Oracle.send_signal( + actor, + unit.model, + fd_kind, + sig=sig, + has_info=has_info, + flags=flags, + ) + target_fd = ( + tc.pick(unit.fds) + if fd_kind == FdKind.NSEXEC + else (99999 if fd_kind == FdKind.CLOSED else unit.mntns_fd) + ) + self.note( + f"{unit.label}: signal(kind={fd_kind.name}, sig={sig}, " + f"fpid={foreign_pidns}) -> {exp or 'ok'}" + ) + info_buf = ctypes.create_string_buffer(128) if has_info else None + info_addr = ctypes.addressof(info_buf) if info_buf is not None else 0 + + def do_sig() -> None: + self.check_call( + "pidfd_send_signal", + exp, + lambda: Sys.pidfd_send_signal( + target_fd, sig, info_addr, flags + ), + ) + + if foreign_pidns and exp is not None: + self.run_in_foreign_pidns(unit.ul_view(), do_sig) + return + + do_sig() + if exp is None and sig == int(signal.SIGKILL): + self._sync_death(unit, os.CLD_KILLED, int(signal.SIGKILL)) + + def _rule_wait_and_poll(self, tc: ChoiceStream) -> None: + avail = self._open_units() + if not avail: + self._rule_open(tc) + return + unit = tc.pick(avail) + self.word("wait") + fd_kind = tc.weighted( + ((8, FdKind.NSEXEC), (1, FdKind.CLOSED), (1, FdKind.NS_MNT)) + ) + neg_fd = fd_kind == FdKind.NSEXEC and tc.draw_int(0, 8) == 0 + options = tc.weighted( + ( + (6, os.WEXITED | os.WNOHANG), + (3, os.WEXITED | os.WNOHANG | os.WNOWAIT), + (1, os.WNOHANG), + (1, os.WEXITED | os.WSTOPPED), + ) + ) + has_ru = tc.draw_int(0, 8) == 0 + nonblock = ( + fd_kind == FdKind.NSEXEC + and not neg_fd + and not has_ru + and options == os.WEXITED + and unit.model.state == State.RUNNING + ) + if tc.draw_int(0, 5) == 0 and unit.model.state == State.RUNNING: + options = os.WEXITED + nonblock = True + foreign_pidns = ( + fd_kind == FdKind.NSEXEC + and not neg_fd + and unit.model.uid_mapped + and (options & os.WNOHANG) != 0 + and tc.draw_int(0, 6) == 0 + ) + actor = Actor(ancestor_pidns=not foreign_pidns) + exp = Oracle.waitid( + actor, + unit.model, + fd_kind, + neg_fd=neg_fd, + options=options, + has_rusage=has_ru, + nonblock=nonblock, + ) + target_fd = ( + -1 + if neg_fd + else ( + tc.pick(unit.fds) + if fd_kind == FdKind.NSEXEC + else (99999 if fd_kind == FdKind.CLOSED else unit.mntns_fd) + ) + ) + self.note( + f"{unit.label}: waitid(kind={fd_kind.name}, opt=0x{options:x}, " + f"nb={nonblock}, fpid={foreign_pidns}) -> {exp or 'ok'}" + ) + + def do_wait() -> None: + if has_ru: + ru = ctypes.create_string_buffer(256) + self.check_call( + "waitid rusage", + exp, + lambda: Sys.waitid_raw( + int(WaitIdType.NSEXEC), + target_fd, + 0, + options, + ctypes.addressof(ru), + ), + ) + return + can_nonblock = ( + nonblock and fd_kind != FdKind.CLOSED and not neg_fd + ) + if can_nonblock: + os.set_blocking(target_fd, False) + try: + res = self.check_call( + "waitid", + exp, + lambda: os.waitid( + int(WaitIdType.NSEXEC), target_fd, options + ), + ) + finally: + if can_nonblock: + os.set_blocking(target_fd, True) + if exp is None and unit.model.state == State.DEAD: + assert res is not None + got = WaitResult( + int(res.si_pid), + int(res.si_status), + int(res.si_code), + int(res.si_uid), + ) + if got != unit.expected_wait: + raise AssertionError( + f"waitid {got} != {unit.expected_wait}" + ) + + if foreign_pidns: + self.run_in_foreign_pidns(unit.ul_view(), do_wait) + else: + do_wait() + + if fd_kind == FdKind.NSEXEC and not neg_fd: + with select.epoll() as ep1, select.epoll() as ep2: + ep1.register(target_fd, select.EPOLLIN | select.EPOLLEXCLUSIVE) + ep2.register(target_fd, select.EPOLLIN | select.EPOLLEXCLUSIVE) + want = unit.model.state == State.DEAD + for ep in (ep1, ep2): + hup = any(ev & select.EPOLLHUP for _, ev in ep.poll(0)) + if hup != want: + raise AssertionError( + f"{unit.label}: EPOLLHUP={hup} != {want}" + ) + + def step(self, tc: ChoiceStream) -> None: + rule = tc.weighted( + ( + (14, self._rule_open), + (10, self._rule_dup_or_close), + (12, self._rule_get_nsfd), + (12, self._rule_share_nsfd), + (20, self._rule_clone), + (6, self._rule_concurrent_bootstrap), + (10, self._rule_retire_or_exit), + (10, self._rule_signal), + (10, self._rule_wait_and_poll), + ) + ) + rule(tc) + + def check_invariants(self) -> None: + for unit in self._units: + for fd in unit.fds: + ul = NsExec.from_fd(fd) + if ul.poll_dead(0) != (unit.model.state == State.DEAD): + raise AssertionError(f"{unit.label}: poll_dead mismatch") + exp = Oracle.waitid( + Actor(), + unit.model, + FdKind.NSEXEC, + options=os.WEXITED | os.WNOHANG, + ) + res = self.check_call( + f"{unit.label} inv wait", + exp, + lambda: ul.wait(os.WNOHANG), + ) + if exp is None: + want = ( + WaitResult(0) + if unit.model.state == State.RUNNING + else unit.expected_wait + ) + if res != want: + raise AssertionError( + f"{unit.label}: inv wait {res} != {want}" + ) + + def close(self) -> None: + for unit in self._units: + for w in unit.workers: + w.ctrl_w = Sys.close_fd(w.ctrl_w) + if not w.autokill and not w.autoreap and w.pid > 0: + with suppress(ChildProcessError, OSError): + self.reap_pid(w.pid) + w.pidfd = Sys.close_fd(w.pidfd) + unit.workers.clear() + unit.init_ctrl_w = Sys.close_fd(unit.init_ctrl_w) + if unit.model.state == State.RUNNING: + if unit.fds: + with suppress(OSError): + unit.ul_view().kill(signal.SIGKILL) + elif unit.init_pidfd >= 0: + with suppress(OSError): + Sys.pidfd_send_signal( + unit.init_pidfd, int(signal.SIGKILL) + ) + for fd in unit.fds: + Sys.close_fd(fd) + unit.fds.clear() + if ( + unit.init_pid > 0 + and not unit.init_autoreap + and not unit.init_reaped + ): + with suppress(ChildProcessError, OSError): + self.reap_pid(unit.init_pid) + unit.init_reaped = True + unit.init_pidfd = Sys.close_fd(unit.init_pidfd) + unit.root_dfd = Sys.close_fd(unit.root_dfd) + unit.mntns_fd = Sys.close_fd(unit.mntns_fd) + self._units.clear() + for fd, _ in self._host_ns.values(): + Sys.close_fd(fd) + self._host_ns.clear() + + +@dataclass +class IdmapSlot: + label: str + ul: NsExec + userns_fd: int + mntns_fd: int + model: UnitModel = field(default_factory=UnitModel) + setgroups_allowed: bool = False + + +class Idmap(NsExecMachine): + """Parametric state machine for userns_set_idmap() and SCM_RIGHTS.""" + + STEPS: ClassVar[int] = 16 + + def __init__(self) -> None: + super().__init__() + self._slots: list[IdmapSlot] = [] + self._seq = 0 + self._has_projid = bool(Path("/proc/self/projid_map").read_bytes()) + self._can_setgroups = ( + os.geteuid() == 0 + and Path("/proc/self/setgroups").read_bytes() == b"allow\n" + ) + + def _open_slot(self) -> IdmapSlot: + if len(self._slots) >= 4: + old = self._slots.pop(0) + Sys.close_fd(old.userns_fd) + Sys.close_fd(old.mntns_fd) + old.ul.close() + ul = NsExec() + slot = IdmapSlot( + label=f"id{self._seq}", + ul=ul, + userns_fd=ul.get_nsfd(CloneFlag.NEWUSER), + mntns_fd=ul.get_nsfd(CloneFlag.NEWNS), + ) + self._seq += 1 + self._slots.append(slot) + return slot + + def _rule_set_idmap(self, tc: ChoiceStream) -> None: + slot = ( + tc.pick(self._slots) + if self._slots and tc.draw_int(0, 3) > 0 + else self._open_slot() + ) + fd_kind = tc.weighted( + ( + (10, FdKind.NS_USER), + (1, FdKind.CLOSED), + (1, FdKind.NSEXEC), + (1, FdKind.NS_MNT), + ) + ) + size = tc.weighted( + ( + (12, UsernsIdmap.SIZE_VER0), + (1, UsernsIdmap.SIZE_VER0 - 1), + (1, PAGE_SIZE + 1), + ) + ) + flags = tc.weighted( + ((8, 0), (2, int(UsernsFlag.SETGROUPS_ALLOWED)), (1, 0x80)) + ) + reserved = 1 if tc.draw_int(0, 10) == 0 else 0 + null_map = tc.draw_int(0, 12) == 0 + ptr_mismatch = not null_map and tc.draw_int(0, 12) == 0 + + u_choice = tc.weighted(((5, True), (4, None), (1, False))) + g_choice = tc.weighted(((5, True), (4, None), (1, False))) + p_choice = ( + tc.weighted(((2, True), (8, None))) if self._has_projid else None + ) + + actor = Actor(can_allow_setgroups=self._can_setgroups) + exp = Oracle.set_idmap( + actor, + slot.model, + fd_kind, + size=size, + flags=flags, + reserved=reserved, + null_map=null_map, + ptr_mismatch=ptr_mismatch, + uid_valid=u_choice, + gid_valid=g_choice, + projid_valid=p_choice, + ) + target_fd = { + FdKind.NS_USER: slot.userns_fd, + FdKind.CLOSED: -1, + FdKind.NSEXEC: slot.ul.fd, + FdKind.NS_MNT: slot.mntns_fd, + }[fd_kind] + if null_map: + self.word("null") + elif size > PAGE_SIZE: + self.word("e2big") + elif ptr_mismatch: + self.word("badptr") + elif flags & int(UsernsFlag.SETGROUPS_ALLOWED): + self.word("setgroups") + elif p_choice: + self.word("projid") + else: + self.word("idmap") + self.note( + f"{slot.label}: set_idmap(fd={fd_kind.name}, sz={size}, " + f"fl=0x{flags:x}, u={u_choice}, g={g_choice}, p={p_choice}) " + f"-> {exp or 'ok'}" + ) + + if null_map: + self.check_call( + "idmap null", + exp, + lambda: Sys.userns_set_idmap_raw(target_fd, 0, size, flags), + ) + return + if size > PAGE_SIZE: + big = ctypes.create_string_buffer(size) + self.check_call( + "idmap E2BIG", + exp, + lambda: Sys.userns_set_idmap_raw( + target_fd, ctypes.addressof(big), size, flags + ), + ) + return + if ptr_mismatch: + bad = ( + UsernsIdmap(nr_uid_extents=1, uid_extents=0) + if tc.draw_bool() + else UsernsIdmap(nr_uid_extents=0, uid_extents=1) + ) + self.check_call( + "idmap ptr mismatch", + exp, + lambda: Sys.userns_set_idmap_raw( + target_fd, ctypes.addressof(bad), size, flags + ), + ) + return + + u_ext = ( + () + if u_choice is None + else (((0, os.geteuid(), 1 if u_choice else 0),)) + ) + g_ext = ( + () + if g_choice is None + else (((0, os.getegid(), 1 if g_choice else 0),)) + ) + p_ext = () if p_choice is None else ((0, 0, 1),) + self.check_call( + "set_userns_idmap", + exp, + lambda: Sys.set_userns_idmap( + target_fd, + uid_extents=u_ext, + gid_extents=g_ext, + projid_extents=p_ext, + reserved=reserved, + size=size, + flags=flags, + ), + ) + if exp is None: + if u_choice: + slot.model.uid_mapped = True + if g_choice: + slot.model.gid_mapped = True + slot.setgroups_allowed = bool( + flags & int(UsernsFlag.SETGROUPS_ALLOWED) + ) + if p_choice: + slot.model.projid_mapped = True + + def _rule_verify_mapped_or_setns(self, tc: ChoiceStream) -> None: + mapped = [ + s + for s in self._slots + if s.model.uid_mapped + and s.model.gid_mapped + and not s.model.has_root + ] + if not mapped: + slot = self._open_slot() + slot.ul.map_self() + slot.model.uid_mapped = True + slot.model.gid_mapped = True + else: + slot = tc.pick(mapped) + self.word("setns") + + rfd = slot.ul.make_mount("tmpfs") + try: + os.mkdir("proc", 0o755, dir_fd=rfd) + Sys.move_mount( + rfd, + "", + slot.mntns_fd, + "/", + MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS, + ) + finally: + os.close(rfd) + pfd = slot.ul.make_mount("proc") + try: + Sys.move_mount( + pfd, + "", + slot.mntns_fd, + "proc", + MoveMountFlag.F_EMPTY_PATH | MoveMountFlag.T_MNTNS, + ) + finally: + os.close(pfd) + slot.model.has_root = True + slot.model.state = State.DEAD + + want_sg = b"allow\n" if slot.setgroups_allowed else b"deny\n" + ready_r, ready_w = os.pipe2(os.O_CLOEXEC) + hold_r, hold_w = os.pipe2(os.O_CLOEXEC) + + def child_check() -> int: + os.close(ready_r) + os.close(hold_w) + Sys.prctl(PrctlOp.SET_DUMPABLE, 1) + ok = ( + os.geteuid() == 0 + and os.getegid() == 0 + and Path("/proc/self/setgroups").read_bytes() == want_sg + ) + os.write(ready_w, b"1" if ok else b"0") + os.close(ready_w) + os.read(hold_r, 1) + os.close(hold_r) + return 0 if ok else 1 + + pid, _ = slot.ul.spawn_fn(child_check) + os.close(ready_w) + os.close(hold_r) + try: + if os.read(ready_r, 1) != b"1": + raise AssertionError(f"{slot.label}: cred/setgroups mismatch") + uts_fd = os.open(f"/proc/{pid}/ns/uts", os.O_RDONLY | os.O_CLOEXEC) + try: + self.run_isolated( + lambda: ( + Sys.setns(slot.userns_fd, CloneFlag.NEWUSER), + Sys.setns(uts_fd, CloneFlag.NEWUTS), + ) + ) + if os.geteuid() == 0: + + def check_foreign() -> None: + self.drop_to_uid(1000) + self.enter_userns_if_unpriv() + self.check_call( + "foreign setns", + errno.EPERM, + lambda: Sys.setns(uts_fd, CloneFlag.NEWUTS), + ) + + self.run_isolated(check_foreign) + finally: + os.close(uts_fd) + finally: + os.close(ready_r) + os.close(hold_w) + if self.reap_pid(pid) != 0 or slot.ul.wait().exit_code != 0: + raise AssertionError("mapped child exited non-zero") + self.note(f"{slot.label}: verified creds, setgroups, and setns") + + def _rule_delegate_idmap(self, tc: ChoiceStream) -> None: + if os.geteuid() != 0: + self._rule_set_idmap(tc) + return + self.word("delegate") + ul = self.create_nsexec_as_uid(1000) + if ul is None: + return + opener_ok = tc.draw_bool() + maps_root = tc.draw_int(0, 3) == 0 + multi = tc.draw_bool() + actor = Actor( + owner=False, + can_allow_setgroups=True, + parent_setid=True, + parent_setfcap=False, + ) + unit = UnitModel() + exp = Oracle.set_idmap( + actor, + unit, + FdKind.NS_USER, + opener_capable=opener_ok, + maps_host_root=maps_root, + multi_extent=multi, + flags=int(UsernsFlag.SETGROUPS_ALLOWED), + uid_valid=True, + gid_valid=True, + ) + self.note( + f"delegate_idmap(opener_ok={opener_ok}, root={maps_root}, " + f"multi={multi}) -> {exp or 'ok'}" + ) + + with ul: + uts_fd = ul.get_nsfd(CloneFlag.NEWUTS) + s_a, s_b = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET) + pid = Sys.fork() + if pid == 0: + s_a.close() + try: + if opener_ok: + self.drop_to_uid(1000) + ufd = ul.get_nsfd(CloneFlag.NEWUSER) + else: + self.drop_to_uid(2000) + ufd = Sys.ioctl(uts_fd, Ioctl.NS_GET_USERNS) + socket.send_fds(s_b, [b"D"], [ufd]) + os.close(ufd) + os._exit(0) + finally: + os.close(uts_fd) + s_b.close() + os.close(uts_fd) + s_b.close() + _, fds, _, _ = socket.recv_fds(s_a, 1, 1) + s_a.close() + if self.reap_pid(pid) != 0 or not fds: + raise AssertionError("failed acquiring delegated userns fd") + delegated_ufd = fds[0] + try: + base_uid = 0 if maps_root else 1000 + u_ext: tuple[tuple[int, int, int], ...] = ( + ((0, base_uid, 1), (1, 2000, 1)) + if multi + else ((0, base_uid, 1),) + ) + g_ext: tuple[tuple[int, int, int], ...] = ( + ((0, 1000, 1), (1, 2000, 1)) if multi else ((0, 1000, 1),) + ) + self.run_isolated( + lambda: ( + Sys.drop_to_setid_helper(990), + self.check_call( + "delegated set_idmap", + exp, + lambda: Sys.set_userns_idmap( + delegated_ufd, + uid_extents=u_ext, + gid_extents=g_ext, + flags=UsernsFlag.SETGROUPS_ALLOWED, + ), + ), + ) + ) + finally: + os.close(delegated_ufd) + + def step(self, tc: ChoiceStream) -> None: + rule = tc.weighted( + ( + (16, self._rule_set_idmap), + (6, self._rule_verify_mapped_or_setns), + (5, self._rule_delegate_idmap), + ) + ) + rule(tc) + + def close(self) -> None: + for slot in self._slots: + Sys.close_fd(slot.userns_fd) + Sys.close_fd(slot.mntns_fd) + slot.ul.close() + self._slots.clear() + + +@dataclass +class MountSlot: + label: str + ul: NsExec + mntns_fd: int + model: UnitModel = field(default_factory=UnitModel) + + +class Mounts(NsExecMachine): + """Parametric state machine for FSCONFIG_SET_NSEXEC and MOVE_MOUNT.""" + + STEPS: ClassVar[int] = 16 + + def __init__(self) -> None: + super().__init__() + self._slots: list[MountSlot] = [] + self._seq = 0 + self._empty_src = tempfile.TemporaryDirectory(prefix="nsexec-mnt-") + + def _open_slot(self, mapped: bool = True) -> MountSlot: + if len(self._slots) >= 4: + old = self._slots.pop(0) + Sys.close_fd(old.mntns_fd) + old.ul.close() + ul = NsExec() + model = UnitModel() + if mapped: + ul.map_self() + model.uid_mapped = True + model.gid_mapped = True + slot = MountSlot( + f"m{self._seq}", ul, ul.get_nsfd(CloneFlag.NEWNS), model + ) + self._seq += 1 + self._slots.append(slot) + return slot + + def _rule_fsconfig(self, tc: ChoiceStream) -> None: + slot = tc.pick(self._slots) if self._slots else self._open_slot() + fstype = tc.weighted( + ( + (4, "tmpfs"), + (3, "ramfs"), + (4, "proc"), + (3, "devpts"), + (2, "mqueue"), + (2, "cgroup2"), + ) + ) + if fstype == "cgroup2" and os.geteuid() != 0: + fstype = "tmpfs" + self.word(fstype) + aux_kind = tc.weighted( + ((10, FdKind.NSEXEC), (1, FdKind.CLOSED), (1, FdKind.NS_MNT)) + ) + foreign_pidns = ( + fstype == "proc" + and aux_kind == FdKind.NSEXEC + and slot.model.uid_mapped + and tc.draw_int(0, 3) == 0 + ) + actor = Actor(ancestor_pidns=not foreign_pidns) + exp = Oracle.fsconfig_nsexec(actor, aux_kind, fstype) + aux_fd = { + FdKind.NSEXEC: slot.ul.fd, + FdKind.CLOSED: 99999, + FdKind.NS_MNT: slot.mntns_fd, + }[aux_kind] + + try: + fsfd = Sys.fsopen(fstype) + except OSError as exc: + if exc.errno in (errno.ENODEV, errno.EPERM): + return + raise + + self.note( + f"{slot.label}: fsconfig({fstype}, aux={aux_kind.name}, " + f"fpid={foreign_pidns}) -> {exp or 'ok'}" + ) + try: + if foreign_pidns: + self.run_in_foreign_pidns( + slot.ul, + lambda: ( + self.check_call( + "proc foreign pidns", + exp, + lambda: Sys.fsconfig( + fsfd, FsconfigCmd.SET_NSEXEC, aux=aux_fd + ), + ), + self.check_call( + "unconfigured proc create", + errno.EBUSY, + lambda: Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE), + ), + ), + ) + return + + self.check_call( + "FSCONFIG_SET_NSEXEC", + exp, + lambda: Sys.fsconfig( + fsfd, FsconfigCmd.SET_NSEXEC, aux=aux_fd + ), + ) + if exp is not None: + return + + if tc.draw_bool(): + re_exp = Oracle.fsconfig_nsexec( + actor, FdKind.NSEXEC, fstype, already_bound=True + ) + self.check_call( + "double SET_NSEXEC", + re_exp, + lambda: Sys.fsconfig( + fsfd, FsconfigCmd.SET_NSEXEC, aux=slot.ul.fd + ), + ) + proc_g_toks: list[str] = [] + if fstype == "proc": + if tc.draw_bool(): + self.check_call( + "proc pidns override", + errno.EBUSY, + lambda: Sys.fsconfig( + fsfd, + FsconfigCmd.SET_STRING, + key="pidns", + value="/proc/self/ns/pid", + ), + ) + if slot.model.uid_mapped: + proc_g_toks = ( + Path("/proc/self/gid_map").read_text().split() + ) + if len(proc_g_toks) >= 3 and int(proc_g_toks[2]) > 1: + self.check_call( + "proc unmapped gid", + errno.EINVAL, + lambda: Sys.fsconfig( + fsfd, + FsconfigCmd.SET_STRING, + key="gid", + value=str(os.getegid() + 1), + ), + ) + Sys.fsconfig( + fsfd, + FsconfigCmd.SET_STRING, + key="gid", + value=str(os.getegid()), + ) + elif fstype == "devpts" and slot.model.uid_mapped: + u_toks = Path("/proc/self/uid_map").read_text().split() + if len(u_toks) >= 3 and int(u_toks[2]) > 1: + self.check_call( + "devpts unmapped uid", + errno.EINVAL, + lambda: Sys.fsconfig( + fsfd, + FsconfigCmd.SET_STRING, + key="uid", + value=str(os.geteuid() + 1), + ), + ) + Sys.fsconfig( + fsfd, + FsconfigCmd.SET_STRING, + key="uid", + value=str(os.geteuid()), + ) + + Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE) + mfd = Sys.fsmount(fsfd) + os.close(mfd) + if fstype == "proc" and slot.model.uid_mapped: + if len(proc_g_toks) >= 3 and int(proc_g_toks[2]) > 1: + self.check_call( + "proc reconfigure unmapped gid", + errno.EINVAL, + lambda: Sys.fsconfig( + fsfd, + FsconfigCmd.SET_STRING, + key="gid", + value=str(os.getegid() + 1), + ), + ) + Sys.fsconfig( + fsfd, + FsconfigCmd.SET_STRING, + key="gid", + value=str(os.getegid()), + ) + Sys.fsconfig(fsfd, FsconfigCmd.CMD_RECONFIGURE) + elif tc.draw_bool(): + self.check_call( + "double fsmount", errno.EBUSY, lambda: Sys.fsmount(fsfd) + ) + finally: + os.close(fsfd) + + def _rule_move_mount(self, tc: ChoiceStream) -> None: + if len(self._slots) < 2: + self._open_slot(mapped=tc.draw_bool()) + slot = tc.pick(self._slots) + peers = [s for s in self._slots if s is not slot] + src_same = not (peers and tc.draw_int(0, 5) == 0) + src_slot = slot if src_same else tc.pick(peers) + target = tc.weighted( + ((5, "/"), (2, "."), (4, "mnt"), (3, "tmp"), (1, "tmp/..")) + ) + t_mntns = tc.draw_int(0, 8) > 0 + clone = not t_mntns or tc.draw_int(0, 6) == 0 + beneath = tc.draw_int(0, 3) == 0 + set_group = tc.draw_int(0, 8) == 0 + self.word("beneath" if beneath else ("clone" if clone else "move")) + + exp = Oracle.move_mount( + Actor(), + slot.model, + src_same_unit=src_same if not clone else True, + target=target, + t_mntns=t_mntns, + clone=clone, + beneath=beneath, + set_group=set_group, + ) + flags = MoveMountFlag(0) + if t_mntns: + flags |= MoveMountFlag.T_MNTNS + if clone: + flags |= MoveMountFlag.CLONE + else: + flags |= MoveMountFlag.F_EMPTY_PATH + if beneath: + flags |= MoveMountFlag.BENEATH + if set_group: + flags |= MoveMountFlag.SET_GROUP + + self.note( + f"{slot.label}: move_mount(target={target!r}, same={src_same}, " + f"cl={clone}, ben={beneath}, sg={set_group}) -> {exp or 'ok'}" + ) + + if clone: + src_dir = self._empty_src.name + to_fd = slot.mntns_fd if t_mntns else Sys.AT_FDCWD + to_path = target if t_mntns else src_dir + + def do_clone_mm() -> None: + if not t_mntns: + self.enter_userns_if_unpriv() + self.check_call( + "move_mount clone", + exp, + lambda: Sys.move_mount( + Sys.AT_FDCWD, src_dir, to_fd, to_path, flags + ), + ) + + if not t_mntns: + self.run_isolated(do_clone_mm) + return + do_clone_mm() + if exp is None: + if target == "/": + slot.model.has_root = True + slot.model.has_dirs = False + else: + slot.model.mount_depth[target] = ( + slot.model.mount_depth.get(target, 0) + 1 + ) + return + + mfd = src_slot.ul.make_mount("tmpfs") + try: + want_dirs = ( + exp is None + and target == "/" + and slot.model.uid_mapped + and slot.model.gid_mapped + and tc.draw_int(0, 3) > 0 + ) + if want_dirs: + for d in ("proc", "tmp", "mnt"): + os.mkdir(d, 0o755, dir_fd=mfd) + self.check_call( + "move_mount", + exp, + lambda: Sys.move_mount(mfd, "", slot.mntns_fd, target, flags), + ) + if exp is None: + if target == "/": + slot.model.has_root = True + slot.model.has_dirs = want_dirs + else: + slot.model.mount_depth[target] = ( + slot.model.mount_depth.get(target, 0) + 1 + ) + finally: + os.close(mfd) + + def _rule_nouser_clone(self, tc: ChoiceStream) -> None: + slot = tc.pick(self._slots) if self._slots else self._open_slot() + self.word("nouser") + exp = Oracle.move_mount( + Actor(), slot.model, src_nouser=True, clone=True + ) + assert exp is not None + self.note( + f"{slot.label}: move_mount(SB_NOUSER clone) -> " + f"{errno.errorcode[exp]}" + ) + + def worker() -> None: + unpriv = os.geteuid() != 0 + self.enter_userns_if_unpriv() + with NsExec() as empty_u: + mfd = empty_u.get_nsfd(CloneFlag.NEWNS) + dst_u = NsExec() if unpriv else None + dst_mfd = ( + dst_u.get_nsfd(CloneFlag.NEWNS) + if dst_u is not None + else slot.mntns_fd + ) + try: + if dst_u is not None and slot.model.has_root: + rfd = dst_u.make_mount("tmpfs") + try: + Sys.move_mount( + rfd, + "", + dst_mfd, + "/", + MoveMountFlag.T_MNTNS + | MoveMountFlag.F_EMPTY_PATH, + ) + finally: + os.close(rfd) + Sys.setns(mfd, CloneFlag.NEWNS) + self.check_call( + "SB_NOUSER clone", + exp, + lambda: Sys.move_mount( + Sys.AT_FDCWD, + "/", + dst_mfd, + "/", + MoveMountFlag.T_MNTNS | MoveMountFlag.CLONE, + ), + ) + finally: + if dst_u is not None: + os.close(dst_mfd) + dst_u.close() + os.close(mfd) + + self.run_isolated(worker) + + def step(self, tc: ChoiceStream) -> None: + rule = tc.weighted( + ( + (14, self._rule_fsconfig), + (16, self._rule_move_mount), + (4, self._rule_nouser_clone), + ) + ) + rule(tc) + + def close(self) -> None: + for slot in self._slots: + Sys.close_fd(slot.mntns_fd) + slot.ul.close() + self._slots.clear() + self._empty_src.cleanup() + + +@dataclass +class LiveCell: + cell: Cell + ro_root: bool + devfs: bool + host_rt: bool + pod_peer: str | None + pivoted: bool = False + mnt_locked: bool = False + mnt_depth: int = 0 + alive: bool = True + + +class Cells(NsExecMachine): + """Realistic multi-Cell supervisor, pods, RO root, PTY, and hot-swap.""" + + STEPS: ClassVar[int] = 16 + MAX_CELLS: ClassVar[int] = 4 + + def __init__(self) -> None: + super().__init__() + self._mgr = CellManager() + self._cells: list[LiveCell] = [] + self._seq = 0 + self._tmp = tempfile.TemporaryDirectory(prefix="nsexec-cells-") + + def _live(self) -> list[LiveCell]: + return [c for c in self._cells if c.alive] + + def _run_session(self, tag: str, sess: Session) -> int: + try: + self._mgr.register_session(tag, sess) + except Exception: + sess.close() + raise + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + for ev in self._mgr.poll_events(0.1): + if ev.kind is EventKind.CELL: + raise AssertionError(f"unexpected cell exit: {ev}") + if ( + ev.kind is EventKind.SESSION + and ev.name == tag + and ev.pid == sess.pid + ): + assert ev.exit_code is not None + return ev.exit_code + raise AssertionError(f"session {tag} timed out") + + def _rule_boot(self, tc: ChoiceStream) -> None: + live = self._live() + if len(live) >= self.MAX_CELLS: + self._rule_stop(tc) + live = self._live() + name = f"c{self._seq}" + self._seq += 1 + ro_root = tc.draw_bool() + devfs = tc.draw_bool() + host_rt = tc.draw_int(0, 3) == 0 + cell = Cell(name) + peer_name: str | None = None + self.word("boot") + try: + if live and tc.draw_bool(): + peer = tc.pick(live) + cell.share_from( + peer.cell, (CloneFlag.NEWNET, CloneFlag.NEWIPC) + ) + peer_name = peer.cell.name + cell.setup_rootfs( + procfs=True, + devfs=devfs, + ro_root=ro_root, + host_runtime=host_rt, + ) + if tc.draw_int(0, 3) == 0: + s_a, s_b = socket.socketpair( + socket.AF_UNIX, socket.SOCK_SEQPACKET + ) + try: + cell.send(s_a) + handed = Cell.recv(name, s_b) + finally: + s_a.close() + s_b.close() + cell.close() + cell = handed + cell.boot() + self._mgr.register_cell(cell) + except Exception: + cell.close() + raise + self._cells.append(LiveCell(cell, ro_root, devfs, host_rt, peer_name)) + if peer_name is not None: + self.word("pod") + self.note( + f"boot {name} (ro={ro_root}, dev={devfs}, rt={host_rt}, " + f"pod={peer_name})" + ) + + def _rule_exec_probe(self, tc: ChoiceStream) -> None: + live = self._live() + if not live: + self._rule_boot(tc) + live = self._live() + lc = tc.pick(live) + if lc.host_rt and tc.draw_bool(): + self.word("argv") + tok = f"tok-{self._seq}-{tc.draw_int(100, 999)}" + code = ( + "import os, sys; " + "ok = os.getpid() > 1 " + "and os.environ.get('CELL_TOKEN') == sys.argv[1]; " + "sys.exit(0 if ok else 1)" + ) + rc = self._run_session( + f"{lc.cell.name}-argv", + lc.cell.exec_argv( + [PYTHON_BIN, "-S", "-c", code, tok], + env={"CELL_TOKEN": tok}, + ), + ) + if rc != 0: + raise AssertionError("exec_argv failed") + self.note(f"{lc.cell.name}: exec_argv(python3, env) -> ok") + return + + ro = lc.ro_root + has_dev = lc.devfs + self.word("exec") + + def probe() -> int: + pids = [e for e in os.listdir("/proc") if e.isdigit()] + if "1" not in pids or str(os.getpid()) not in pids: + return 1 + if len(os.listdir("/proc/1/fd")) > 4: + return 4 + if has_dev: + Path("/dev/null").write_bytes(b"discard") + if Path("/dev/null").read_bytes() != b"": + return 5 + ufd = os.open("/dev/urandom", os.O_RDONLY | os.O_CLOEXEC) + try: + if len(os.read(ufd, 8)) != 8: + return 6 + finally: + os.close(ufd) + Path("/tmp/ok").write_bytes(b"rw") + Sys.unshare(CloneFlag.NEWUTS | CloneFlag.NEWIPC | CloneFlag.NEWNET) + try: + Path("/ro-test").write_bytes(b"x") + except OSError as exc: + return 0 if (ro and exc.errno == errno.EROFS) else 2 + return 3 if ro else 0 + + rc = self._run_session( + f"{lc.cell.name}-probe", lc.cell.exec_fn(probe) + ) + if rc != 0: + raise AssertionError( + f"{lc.cell.name}: fs/ns probe failed (rc={rc})" + ) + self.note(f"{lc.cell.name}: exec_fn(ro={ro}, dev={has_dev}) -> ok") + + def _rule_pty_and_pod_ipc(self, tc: ChoiceStream) -> None: + dev_cells = [c for c in self._live() if c.devfs] + if not dev_cells: + self._rule_boot(tc) + return + lc = tc.pick(dev_cells) + self.word("pty") + msg = f"pty-{self._seq}-{tc.draw_int(10, 99)}".encode("ascii") + + def check_pty() -> int: + if not os.path.exists("/dev/pts/ptmx"): + return 0 + m_fd, s_fd = pty.openpty() + try: + os.write(s_fd, msg + b"\n") + return 0 if msg in os.read(m_fd, 64) else 1 + finally: + os.close(m_fd) + os.close(s_fd) + + with lc.cell.exec_fn(check_pty) as sess: + if sess.wait() != 0: + raise AssertionError("pty roundtrip failed") + + mates = [ + o + for o in dev_cells + if o is not lc + and (o.cell.name == lc.pod_peer or lc.cell.name == o.pod_peer) + ] + if mates: + mate = mates[0] + qname = f"/q{self._seq}_{tc.draw_int(1, 99)}".encode("ascii") + bare = qname[1:].decode("ascii") + + def mk_q() -> int: + if not os.path.ismount("/dev/mqueue"): + return 10 + mqd: int = Sys._LIBC.mq_open( + ctypes.c_char_p(qname), + ctypes.c_int(os.O_CREAT | os.O_RDWR), + ctypes.c_uint(0o600), + ctypes.c_void_p(0), + ) + if mqd < 0: + return 11 + os.close(mqd) + return 0 + + with lc.cell.exec_fn(mk_q) as s1: + if s1.wait() == 0: + with mate.cell.exec_fn( + lambda: ( + 0 + if ( + bare in os.listdir("/dev/mqueue") + and Sys._LIBC.mq_unlink(ctypes.c_char_p(qname)) + == 0 + ) + else 1 + ) + ) as s2: + if s2.wait() != 0: + raise AssertionError("pod mqueue not shared") + self.note(f"{lc.cell.name}: pty + pod mqueue -> ok") + + def _rule_hot_swap_or_autokill(self, tc: ChoiceStream) -> None: + live = self._live() + if not live: + self._rule_boot(tc) + live = self._live() + lc = tc.pick(live) + + if tc.draw_bool(): + if lc.mnt_depth == 0: + self.word("mount") + if tc.draw_bool(): + sub = Path(self._tmp.name) / f"b{self._seq}" + self._seq += 1 + sub.mkdir(mode=0o755, exist_ok=True) + (sub / "v").write_bytes(b"bind") + lc.cell.bind_mount(str(sub), "mnt") + lc.mnt_locked = True + else: + lc.cell.mount_fs("tmpfs", "mnt") + with lc.cell.exec_fn( + lambda: (Path("/mnt/v").write_bytes(b"v1"), 0)[1] + ) as s: + s.wait() + lc.mnt_locked = False + lc.mnt_depth = 1 + self.note( + f"{lc.cell.name}: hot mount /mnt (locked={lc.mnt_locked})" + ) + return + + self.word("swap") + m2 = lc.cell.ul.make_mount("tmpfs") + try: + vfd = os.open( + "v", + os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC, + 0o644, + dir_fd=m2, + ) + os.write(vfd, b"v2") + os.close(vfd) + Sys.move_mount( + m2, + "", + lc.cell.mntns_fd, + "mnt", + MoveMountFlag.F_EMPTY_PATH + | MoveMountFlag.T_MNTNS + | MoveMountFlag.BENEATH, + ) + lc.mnt_depth += 1 + finally: + os.close(m2) + + locked = lc.mnt_locked + + def peel() -> int: + Sys.umount2("/mnt", UmountFlag.DETACH) + if Path("/mnt/v").read_bytes() != b"v2": + return 3 + if locked: + try: + Sys.umount2("/mnt", UmountFlag.DETACH) + except OSError as exc: + return 0 if exc.errno == errno.EINVAL else 1 + return 2 + return 0 + + with lc.cell.exec_fn(peel) as s: + if s.wait() != 0: + raise AssertionError("MOVE_MOUNT_BENEATH swap failed") + lc.mnt_depth -= 1 + self.note(f"{lc.cell.name}: beneath swap (locked={locked}) -> ok") + return + + r_p, w_p = os.pipe2(os.O_CLOEXEC) + hr_p, hw_p = os.pipe2(os.O_CLOEXEC) + try: + self.word("autokill") + + def sleeper() -> int: + os.close(r_p) + os.close(hr_p) + if Sys.fork() == 0: + os.close(w_p) + os.close(hw_p) + os._exit(0) + os.write(w_p, b"S") + os.close(w_p) + signal.pause() + return 0 + + sess = lc.cell.exec_fn(sleeper, autokill=True) + except Exception: + for fd in (r_p, w_p, hr_p, hw_p): + Sys.close_fd(fd) + raise + os.close(w_p) + os.close(hw_p) + os.read(r_p, 1) + os.close(r_p) + try: + dup_fd = os.dup(sess.pidfd) + try: + sess.close() + poller = select.poll() + poller.register(hr_p, select.POLLIN) + if poller.poll(0): + raise AssertionError("autokill fired before last close") + finally: + os.close(dup_fd) + poller = select.poll() + poller.register(hr_p, select.POLLIN) + if not poller.poll(5000) or os.read(hr_p, 1) != b"": + raise AssertionError("autokill did not terminate session") + finally: + os.close(hr_p) + self.note(f"{lc.cell.name}: autokill refcount + orphan reap -> ok") + + def _rule_pivot(self, tc: ChoiceStream) -> None: + cands = [ + c + for c in self._live() + if not c.ro_root + and not c.devfs + and not c.host_rt + and not c.pivoted + and c.mnt_depth == 0 + ] + if not cands: + self._rule_stop(tc) + return + lc = tc.pick(cands) + self.word("pivot") + + def do_pivot() -> int: + fsfd = Sys.fsopen("tmpfs") + Sys.fsconfig(fsfd, FsconfigCmd.CMD_CREATE) + mfd = Sys.fsmount(fsfd) + os.close(fsfd) + for d in ("old", "mnt", "tmp", "proc"): + os.mkdir(d, 0o755, dir_fd=mfd) + Sys.move_mount( + mfd, "", Sys.AT_FDCWD, "/mnt", MoveMountFlag.F_EMPTY_PATH + ) + os.close(mfd) + os.chdir("/mnt") + Sys.pivot_root(".", "old") + os.chdir("/") + Sys.umount2("/old", UmountFlag.DETACH) + return 0 + + with lc.cell.exec_fn(do_pivot) as s: + if s.wait() != 0: + raise AssertionError(f"{lc.cell.name}: pivot_root failed") + lc.cell.root_dfd = Sys.close_fd(lc.cell.root_dfd) + lc.cell.mount_fs("proc", "proc") + lc.pivoted = True + self.note(f"{lc.cell.name}: pivot_root + external proc remount -> ok") + + def _rule_stop(self, tc: ChoiceStream) -> None: + live = self._live() + if not live: + self._rule_boot(tc) + return + self.word("stop") + lc = tc.pick(live) + if tc.draw_bool(): + rc = tc.draw_int(0, 30) + res = lc.cell.shutdown(rc) + exp: int | None = rc + else: + lc.cell.kill(signal.SIGKILL) + res = lc.cell.wait() + exp = -int(signal.SIGKILL) + lc.alive = False + evs = self._mgr.poll_events(1.0) + got = [ + e + for e in evs + if e.kind is EventKind.CELL and e.name == lc.cell.name + ] + if not got or got[0].exit_code != exp or res.exit_code != exp: + raise AssertionError( + f"{lc.cell.name}: stop expected {exp}, got {res}/{got}" + ) + lc.cell.close() + self.note(f"{lc.cell.name}: stopped exit={exp}") + + def step(self, tc: ChoiceStream) -> None: + rule = tc.weighted( + ( + (16, self._rule_boot), + (14, self._rule_exec_probe), + (12, self._rule_pty_and_pod_ipc), + (14, self._rule_hot_swap_or_autokill), + (6, self._rule_pivot), + (8, self._rule_stop), + ) + ) + rule(tc) + + def check_invariants(self) -> None: + for lc in self._cells: + if lc.alive and lc.cell.ul.poll_dead(0): + raise AssertionError(f"{lc.cell.name}: died unexpectedly") + + def close(self) -> None: + self._mgr.close() + for lc in self._cells: + lc.cell.close() + self._cells.clear() + self._tmp.cleanup() + + +class _LandlockRulesetAttr(ctypes.Structure): + _fields_ = [ + ("handled_access_fs", ctypes.c_uint64), + ("handled_access_net", ctypes.c_uint64), + ("scoped", ctypes.c_uint64), + ("quiet_access_fs", ctypes.c_uint64), + ("quiet_access_net", ctypes.c_uint64), + ("quiet_scoped", ctypes.c_uint64), + ("handled_permissions", ctypes.c_uint64), + ] + + +class _LandlockNamespaceAttr(ctypes.Structure): + _fields_ = [ + ("permissions", ctypes.c_uint64), + ("allowed_namespace_types", ctypes.c_uint64), + ("quiet_namespace_types", ctypes.c_uint64), + ] + + +class Landlock(NsExecMachine): + """Parametric Landlock LANDLOCK_PERMISSION_NAMESPACE_USE state machine.""" + + STEPS: ClassVar[int] = 14 + + def __init__(self) -> None: + super().__init__() + self._has_timens = os.path.exists("/proc/self/ns/time") + try: + abi = Sys.syscall( + "landlock_create_ruleset", + ctypes.c_void_p(0), + ctypes.c_size_t(0), + ctypes.c_uint32(1), + ) + except OSError as exc: + if exc.errno in (errno.ENOSYS, errno.EOPNOTSUPP): + raise SkipScenario("Landlock not enabled") from exc + raise + if abi < 12: + raise SkipScenario(f"Landlock ABI {abi} < 12") + + @staticmethod + def _restrict(allowed_mask: int) -> None: + rattr = _LandlockRulesetAttr(handled_permissions=1) + rfd = Sys.syscall( + "landlock_create_ruleset", + ctypes.c_void_p(ctypes.addressof(rattr)), + ctypes.c_size_t(ctypes.sizeof(rattr)), + ctypes.c_uint32(0), + ) + try: + if allowed_mask: + nattr = _LandlockNamespaceAttr( + permissions=1, + allowed_namespace_types=allowed_mask, + quiet_namespace_types=0, + ) + Sys.syscall( + "landlock_add_rule", + ctypes.c_int(rfd), + ctypes.c_int(3), + ctypes.c_void_p(ctypes.addressof(nattr)), + ctypes.c_uint32(0), + ) + Sys.syscall( + "landlock_restrict_self", + ctypes.c_int(rfd), + ctypes.c_uint32((1 << 4) | (1 << 0)), + ) + finally: + os.close(rfd) + + def step(self, tc: ChoiceStream) -> None: + shareable = [ + CloneFlag.NEWCGROUP, + CloneFlag.NEWIPC, + CloneFlag.NEWUTS, + CloneFlag.NEWNET, + ] + if self._has_timens: + shareable.append(CloneFlag.NEWTIME) + all_types = [ + CloneFlag.NEWUSER, + CloneFlag.NEWNS, + CloneFlag.NEWPID, + *shareable, + ] + + allowed = 0 + for flag in all_types: + if tc.draw_int(0, 2) > 0: + allowed |= int(flag) + shared_flags = [f for f in shareable if tc.draw_bool()] + shared_mask = 0 + for flag in shared_flags: + shared_mask |= int(flag) + active_mask = 0 + for flag in all_types: + active_mask |= int(flag) + probe_flag = tc.pick(shareable) + self.word(NS_NAMES[probe_flag]) + + actor = Actor(landlock_mask=allowed) + unit = UnitModel(has_root=True, shared_host_mask=shared_mask) + exp_open = Oracle.open(actor, int(NsExecFlag.DEFAULT), active_mask) + exp_share = Oracle.share_nsfd( + actor, + UnitModel(), + FdKind.NS_SHAREABLE, + int(probe_flag), + has_timens=self._has_timens, + ) + exp_clone = Oracle.clone_into( + actor, + unit, + FdKind.NSEXEC, + extra_flags=int(CloneFlag.AUTOREAP), + exit_signal=0, + active_ns_mask=active_mask, + ) + self.note( + f"landlock(allow=0x{allowed:x}, shared=0x{shared_mask:x}, " + f"probe={NS_NAMES[probe_flag]}) -> " + f"open={exp_open or 0}, share={exp_share or 0}, " + f"clone={exp_clone or 0}" + ) + + def worker() -> None: + with ExitStack() as stack: + cell = stack.enter_context(Cell("ll")) + if shared_flags: + cell.share_host(shared_flags) + cell.setup_rootfs(procfs=False) + dst = stack.enter_context(NsExec()) + src_ns = cell.ul.get_nsfd(probe_flag) + stack.callback(Sys.close_fd, src_ns) + + self._restrict(allowed) + + opened = self.check_call("ll open", exp_open, NsExec) + if opened is not None: + opened.close() + self.check_call( + "ll share", exp_share, lambda: dst.share_nsfd(src_ns) + ) + if exp_clone is None: + pid, _ = cell.ul.spawn_fn( + lambda: 0, extra_flags=CloneFlag.AUTOREAP + ) + if pid <= 0 or cell.wait().exit_code != 0: + raise AssertionError("allowed ll clone failed") + else: + self.check_call( + "ll clone", + exp_clone, + lambda: cell.ul.clone_into( + CloneFlag.AUTOREAP, exit_signal=0 + ), + ) + + self.run_isolated(worker) + + +@dataclass(frozen=True) +class Scenario: + name: str + machine_cls: type[NsExecMachine] + default_cases: int + + +DEFAULT_CASES: Final[int] = 4 + +SCENARIOS: Final[tuple[Scenario, ...]] = ( + Scenario("lifecycle", Lifecycle, DEFAULT_CASES), + Scenario("idmap", Idmap, DEFAULT_CASES), + Scenario("mounts", Mounts, DEFAULT_CASES), + Scenario("cells", Cells, DEFAULT_CASES), + Scenario("landlock", Landlock, DEFAULT_CASES), +) + +SCENARIO_MAP: Final[dict[str, Scenario]] = {s.name: s for s in SCENARIOS} + + +@dataclass(frozen=True) +class SuiteRunner: + selected: Sequence[Scenario] + seed: int + cases_override: int | None + steps_override: int | None + case: int | None + + @staticmethod + def probe_nsexec() -> tuple[bool, str]: + try: + ul = NsExec() + except OSError as exc: + if exc.errno in SKIP_ERRNOS: + return False, f"nsexec_open() unavailable: {exc}" + raise + with ul: + try: + ul.map_self() + mfd = ul.make_mount("tmpfs") + except OSError as exc: + return False, f"nsexec setup unavailable: {exc}" + try: + os.mkdir("probe", 0o755, dir_fd=mfd) + finally: + os.close(mfd) + return True, "" + + @staticmethod + def _load_ksft() -> Any: + ksft_dir = str(Path(__file__).resolve().parents[1] / "kselftest") + if ksft_dir not in sys.path: + sys.path.insert(0, ksft_dir) + return importlib.import_module("ksft") + + def _config_for(self, spec: Scenario) -> RunConfig: + cases = ( + self.cases_override + if self.cases_override is not None + else spec.default_cases + ) + return RunConfig( + seed=self.seed, + cases=cases, + steps=self.steps_override, + case=self.case, + ) + + @staticmethod + def _planned(cfg: RunConfig) -> int: + return 1 if cfg.case is not None else cfg.cases + + @staticmethod + def _case_label(name: str, idx: int) -> str: + return f"{name}.{idx:02d}" + + def run_ktap(self) -> int: + ksft = self._load_ksft() + supported, skip_reason = self.probe_nsexec() + configs = [(spec, self._config_for(spec)) for spec in self.selected] + ksft.print_header() + ksft.set_plan(sum(self._planned(cfg) for _, cfg in configs)) + ksft.print_msg( + f"seed 0x{self.seed:016x} " + f"(replay: NSEXEC_SEED=0x{self.seed:016x})" + ) + sys.stdout.flush() + + for spec, cfg in configs: + planned = self._planned(cfg) + if not supported: + ksft.print_msg(f"{spec.name}: {skip_reason}") + for idx in range(planned): + ksft.test_result_skip(self._case_label(spec.name, idx)) + sys.stdout.flush() + continue + + emitted = 0 + try: + for res in Machine.iter_cases( + spec.name, spec.machine_cls, cfg + ): + label = ( + f"{spec.name}.{res.name}" + if res.name + else self._case_label(spec.name, emitted) + ) + emitted += 1 + if res.failure is None: + ksft.test_result_pass(label) + else: + report = res.failure.format_report( + seed=self.seed, cmd="./test_smoke.sh" + ) + for line in report.splitlines(): + ksft.print_msg(line) + ksft.test_result_fail(label) + sys.stdout.flush() + except SkipScenario as exc: + ksft.print_msg(f"{spec.name}: {exc}") + for idx in range(emitted, planned): + ksft.test_result_skip(self._case_label(spec.name, idx)) + sys.stdout.flush() + + ksft.print_cnts() + sys.stdout.flush() + counts: dict[str, int] = ksft.ksft_cnt + if counts["fail"] > 0: + return int(ksft.KSFT_FAIL) + if counts["pass"] == 0 and counts["skip"] > 0: + return int(ksft.KSFT_SKIP) + return int(ksft.KSFT_PASS) + + def run_cli(self) -> int: + supported, skip_reason = self.probe_nsexec() + if not supported: + print(f"SKIP: {skip_reason}") + return 4 + + print(f"seed 0x{self.seed:016x}", flush=True) + + tty = sys.stderr.isatty() + ok = True + for spec in self.selected: + cfg = self._config_for(spec) + t0 = time.monotonic() + + def on_prog( + msg: str, name: str = spec.name, started: float = t0 + ) -> None: + if tty: + dt = time.monotonic() - started + sys.stderr.write(f"\r\x1b[K{name:<12} {msg} {dt:.1f}s") + sys.stderr.flush() + + try: + failure = Machine.run( + spec.name, spec.machine_cls, cfg, progress=on_prog + ) + except SkipScenario as exc: + if tty: + sys.stderr.write("\r\x1b[K") + print(f"{spec.name:<12} skipped ({exc})", flush=True) + continue + + if tty: + sys.stderr.write("\r\x1b[K") + sys.stderr.flush() + dt = time.monotonic() - t0 + verdict = "passed" if failure is None else "failed" + print( + f"{spec.name:<12} {verdict} {self._planned(cfg):>3} cases " + f"{dt:>7.1f}s", + flush=True, + ) + if failure is not None: + ok = False + print( + failure.format_report(seed=self.seed, cmd="./selftest.py"), + flush=True, + ) + return 0 if ok else 1 + + +def _env_int(name: str) -> int | None: + raw = os.environ.get(name) + return int(raw, 0) if raw else None + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Model-based stochastic selftest for nsexec(2)." + ) + parser.add_argument("--ktap", action="store_true") + parser.add_argument("--seed", type=Machine.parse_seed, default=None) + parser.add_argument("--cases", type=int, default=None) + parser.add_argument("--steps", type=int, default=None) + parser.add_argument("--case", type=int, default=None) + parser.add_argument( + "scenarios", + nargs="*", + choices=[s.name for s in SCENARIOS], + ) + ns = parser.parse_args(argv) + + env_seed = os.environ.get("NSEXEC_SEED") + if ns.seed is not None: + seed = ns.seed + elif env_seed: + seed = Machine.parse_seed(env_seed) + else: + seed = Machine.generate_seed() + cases = ns.cases if ns.cases is not None else _env_int("NSEXEC_CASES") + steps = ns.steps if ns.steps is not None else _env_int("NSEXEC_STEPS") + case = ns.case if ns.case is not None else _env_int("NSEXEC_CASE") + if case is not None and case < 0: + print("error: case index must be non-negative", file=sys.stderr) + return 2 + selected = ( + [SCENARIO_MAP[name] for name in ns.scenarios] + if ns.scenarios + else list(SCENARIOS) + ) + + runner = SuiteRunner(selected, seed, cases, steps, case) + return runner.run_ktap() if ns.ktap else runner.run_cli() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/testing/selftests/nsexec/settings b/tools/testing/selftests/nsexec/settings new file mode 100644 index 000000000000..6091b45d226b --- /dev/null +++ b/tools/testing/selftests/nsexec/settings @@ -0,0 +1 @@ +timeout=120 diff --git a/tools/testing/selftests/nsexec/test_smoke.sh b/tools/testing/selftests/nsexec/test_smoke.sh new file mode 100755 index 000000000000..2b81ae184058 --- /dev/null +++ b/tools/testing/selftests/nsexec/test_smoke.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 + +ksft_skip=4 + +command -v python3 >/dev/null 2>&1 || exit $ksft_skip +python3 -c 'import ctypes, sys; sys.exit(sys.version_info < (3, 11))' \ + 2>/dev/null || exit $ksft_skip + +DIR="$(dirname "$(readlink -f "$0")")" +exec python3 "$DIR/selftest.py" --ktap "$@" -- 2.47.3