#!/usr/bin/env python3 """Probe Linux memfd file seals without opening existing files or devices. Requires Linux 6.3+ and Python 3.8+ with os.memfd_create. No third-party modules. Uses explicit non-executable memfds, not the host's default execution policy. """ import argparse from contextlib import contextmanager from datetime import datetime, timezone import errno import fcntl import hashlib import json import mmap import os from pathlib import Path import platform # Linux UAPI values, pinned at v6.12/include/uapi/linux/{fcntl,memfd}.h. FUTURE_WRITE = getattr(fcntl, "F_SEAL_FUTURE_WRITE", 0x0010) NOEXEC_SEAL = getattr(os, "MFD_NOEXEC_SEAL", 0x0008) EXEC_SEAL = getattr(fcntl, "F_SEAL_EXEC", 0x0020) PAGE = mmap.PAGESIZE def require(condition, message): if not condition: raise RuntimeError(message) def add(fd, seals): require(fcntl.fcntl(fd, fcntl.F_ADD_SEALS, seals) == 0, "F_ADD_SEALS result") def get(fd): return fcntl.fcntl(fd, fcntl.F_GET_SEALS) def expect_errno(operation, expected): try: result = operation() except OSError as error: require(error.errno == expected, f"Expected {expected}, got {error.errno}") return errno.errorcode[error.errno] else: if isinstance(result, mmap.mmap): result.close() raise RuntimeError(f"Expected {errno.errorcode[expected]}, operation succeeded") def payload(first=b"A", size=PAGE): return first + b"\0" * (size - 1) def check_bytes(fd, first=b"A", size=PAGE): require(os.fstat(fd).st_size == size, "Unexpected file size") require(os.pread(fd, size + 1, 0) == payload(first, size), "Unexpected complete file payload") def shared(fd): return mmap.mmap(fd, PAGE, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ | mmap.PROT_WRITE) @contextmanager def fresh(): fd = os.memfd_create("hesela-file-seals", os.MFD_CLOEXEC | os.MFD_ALLOW_SEALING | NOEXEC_SEAL) try: os.ftruncate(fd, PAGE) require(os.pwrite(fd, payload(), 0) == PAGE, "Short initial write") require(get(fd) == EXEC_SEAL, "Expected only initial F_SEAL_EXEC") check_bytes(fd) yield fd finally: os.close(fd) def write_mapping_busy(): with fresh() as fd: with shared(fd): busy = expect_errno(lambda: add(fd, fcntl.F_SEAL_WRITE), errno.EBUSY) require(get(fd) & fcntl.F_SEAL_WRITE == 0, "Failed call installed WRITE") add(fd, fcntl.F_SEAL_WRITE) require(get(fd) & fcntl.F_SEAL_WRITE != 0, "WRITE absent after unmapping") check_bytes(fd) return {"while_shared_mapping": busy, "after_unmap": "WRITE installed", "file_byte": "A"} def readonly_mapping_busy(): with fresh() as fd: with mmap.mmap(fd, PAGE, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ) as reader: require(reader[:] == payload(), "Read-only mapping differs") busy = expect_errno(lambda: add(fd, fcntl.F_SEAL_WRITE), errno.EBUSY) require(get(fd) & fcntl.F_SEAL_WRITE == 0, "Failed call installed WRITE") check_bytes(fd) add(fd, fcntl.F_SEAL_WRITE) require(get(fd) & fcntl.F_SEAL_WRITE != 0, "WRITE absent after read-only unmapping") check_bytes(fd) return {"mapping_protection": "PROT_READ", "descriptor_access": "O_RDWR", "while_shared_mapping": busy, "after_unmap": "WRITE installed", "file_byte": "A"} def future_write(): with fresh() as fd: with shared(fd) as mapping: add(fd, FUTURE_WRITE) require(get(fd) & FUTURE_WRITE != 0, "FUTURE_WRITE absent") mapping[0:1] = b"B" check_bytes(fd, b"B") write_error = expect_errno(lambda: os.pwrite(fd, b"C", 0), errno.EPERM) map_error = expect_errno(lambda: shared(fd), errno.EPERM) with mmap.mmap(fd, PAGE, flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ | mmap.PROT_WRITE) as private: private[0:1] = b"P" require(private[0:1] == b"P", "Private edit not visible") check_bytes(fd, b"B") busy = expect_errno(lambda: add(fd, fcntl.F_SEAL_WRITE), errno.EBUSY) add(fd, fcntl.F_SEAL_WRITE) require(get(fd) & (FUTURE_WRITE | fcntl.F_SEAL_WRITE) == (FUTURE_WRITE | fcntl.F_SEAL_WRITE), "Seal union missing") check_bytes(fd, b"B") return {"existing_shared_file_byte": "B", "pwrite": write_error, "new_shared_mapping": map_error, "private_byte": "P", "file_after_private": "B", "upgrade_while_mapped": busy, "upgrade_after_unmap": "WRITE installed"} def write_without_size(): with fresh() as fd: add(fd, fcntl.F_SEAL_WRITE) require(get(fd) & fcntl.F_SEAL_WRITE != 0, "WRITE absent before resize") os.ftruncate(fd, PAGE * 2) check_bytes(fd, size=PAGE * 2) os.ftruncate(fd, PAGE // 2) check_bytes(fd, size=PAGE // 2) return {"grown_bytes": PAGE * 2, "shrunk_bytes": PAGE // 2, "file_byte": "A"} def fixed_content_size(): with fresh() as fd: seals = fcntl.F_SEAL_WRITE | fcntl.F_SEAL_SHRINK | fcntl.F_SEAL_GROW add(fd, seals) require(get(fd) & seals == seals, "Combined seals absent") errors = { "pwrite": expect_errno(lambda: os.pwrite(fd, b"B", 0), errno.EPERM), "new_shared_mapping": expect_errno(lambda: shared(fd), errno.EPERM), "shrink": expect_errno(lambda: os.ftruncate(fd, PAGE // 2), errno.EPERM), "grow": expect_errno(lambda: os.ftruncate(fd, PAGE * 2), errno.EPERM), } with mmap.mmap(fd, PAGE, flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ | mmap.PROT_WRITE) as private: private[0:1] = b"P" require(private[0:1] == b"P", "Private edit not visible") with mmap.mmap(fd, PAGE, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ) as reader: require(reader[:] == payload(), "Read-only mapping differs") check_bytes(fd) return {**errors, "private_byte": "P", "file_byte": "A", "file_bytes": PAGE} def seal_list_only(): with fresh() as fd: duplicate = os.dup(fd) try: add(fd, fcntl.F_SEAL_SEAL) require(get(fd) & fcntl.F_SEAL_SEAL != 0, "SEAL absent") require(get(fd) == get(duplicate), "Duplicate descriptor has different seals") locked = expect_errno(lambda: add(duplicate, fcntl.F_SEAL_WRITE), errno.EPERM) require(os.pwrite(duplicate, b"B", 0) == 1, "Short write via duplicate") os.ftruncate(duplicate, PAGE * 2) check_bytes(fd, b"B", PAGE * 2) return {"add_write_via_duplicate": locked, "write_via_duplicate": "B", "grown_bytes": PAGE * 2, "same_seals": True} finally: os.close(duplicate) def shrink_only(): with fresh() as fd: add(fd, fcntl.F_SEAL_SHRINK) require(get(fd) & fcntl.F_SEAL_SHRINK != 0, "SHRINK absent") with shared(fd) as mapping: denied = expect_errno(lambda: os.ftruncate(fd, PAGE // 2), errno.EPERM) mapping[0:1] = b"B" os.ftruncate(fd, PAGE * 2) check_bytes(fd, b"B", PAGE * 2) return {"shrink": denied, "shared_file_byte": "B", "grown_bytes": PAGE * 2} CASES = [write_mapping_busy, readonly_mapping_busy, future_write, write_without_size, fixed_content_size, seal_list_only, shrink_only] def run(repetitions): require(isinstance(repetitions, int) and not isinstance(repetitions, bool) and 1 <= repetitions <= 100, "repetitions must be an integer from 1 to 100") require(platform.system() == "Linux" and hasattr(os, "memfd_create"), "Linux memfd support required") required = ["F_ADD_SEALS", "F_GET_SEALS", "F_SEAL_WRITE", "F_SEAL_SHRINK", "F_SEAL_GROW", "F_SEAL_SEAL"] require(all(hasattr(fcntl, name) for name in required), "Python fcntl build lacks required Linux seal constants") observations = [{case.__name__: case() for case in CASES} for _ in range(repetitions)] require(all(row == observations[0] for row in observations), "Repetitions differ") return { "schemaVersion": 1, "experiment": "linux-memfd-file-seals", "generatedAt": datetime.now(timezone.utc).isoformat(), "environment": {"kernel": platform.release(), "python": platform.python_version(), "pageSizeBytes": PAGE, "initialSealMask": EXEC_SEAL, "memfdFlags": ["MFD_CLOEXEC", "MFD_ALLOW_SEALING", "MFD_NOEXEC_SEAL"]}, "repetitions": repetitions, "casesPerRepetition": len(CASES), "sourceSha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "observations": observations, "limits": ["Sequential operations on one host; no concurrent writers or descriptor passing between processes.", "No reboot, power loss, device I/O, crash recovery, performance or reliability-rate measurement.", "No huge pages, executable mappings, asynchronous I/O or memory-pinning test.", "Each case uses a fresh volatile memfd; no existing files or block devices are modified."], } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repetitions", type=int, default=3) parser.add_argument("--output", type=Path) args = parser.parse_args() result = json.dumps(run(args.repetitions), indent=2) + "\n" if args.output: with args.output.open("x", encoding="utf-8") as output: output.write(result) else: print(result, end="") if __name__ == "__main__": main()