#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Sequential Linux memfd mapping-capability controls; no existing files modified. Requires 64-bit Linux 6.3+, Python 3.8+, libc, procfs and permitted memfd calls. Uses ctypes only for mmap/mprotect/munmap on fresh, one-page anonymous files. """ import argparse from contextlib import contextmanager import ctypes from datetime import datetime, timezone import errno import fcntl import hashlib import json import mmap import os from pathlib import Path import platform PAGE = mmap.PAGESIZE FUTURE_WRITE = getattr(fcntl, "F_SEAL_FUTURE_WRITE", 0x10) NOEXEC_SEAL = getattr(os, "MFD_NOEXEC_SEAL", 0x08) EXEC_SEAL = getattr(fcntl, "F_SEAL_EXEC", 0x20) READ = mmap.PROT_READ WRITE = mmap.PROT_WRITE LIBC = ctypes.CDLL(None, use_errno=True) LIBC.mmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_long] LIBC.mmap.restype = ctypes.c_void_p LIBC.mprotect.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int] LIBC.mprotect.restype = ctypes.c_int LIBC.munmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t] LIBC.munmap.restype = ctypes.c_int def require(condition, message): if not condition: raise RuntimeError(message) def payload(first=b"A"): return first + b"\0" * (PAGE - 1) def check(fd, address, first=b"A"): expected = payload(first) require(os.fstat(fd).st_size == PAGE, "File extent changed") require(os.pread(fd, PAGE + 1, 0) == expected, "Complete file payload mismatch") require(ctypes.string_at(address, PAGE) == expected, "Complete mapped payload mismatch") def add(fd, mask): require(fcntl.fcntl(fd, fcntl.F_ADD_SEALS, mask) == 0, "Seal call failed") require(fcntl.fcntl(fd, fcntl.F_GET_SEALS) & mask == mask, "Seal not installed") def expect_errno(operation, expected): try: operation() except OSError as error: require(error.errno == expected, f"Expected {expected}, got {error.errno}") return errno.errorcode[error.errno] raise RuntimeError(f"Expected {errno.errorcode[expected]}, operation succeeded") def protect(address, protection): ctypes.set_errno(0) if LIBC.mprotect(address, PAGE, protection) != 0: code = ctypes.get_errno() raise OSError(code, os.strerror(code)) @contextmanager def mapping(fd, protection): address = LIBC.mmap(None, PAGE, protection, mmap.MAP_SHARED, fd, 0) if address == ctypes.c_void_p(-1).value: code = ctypes.get_errno() raise OSError(code, os.strerror(code)) try: yield address finally: require(LIBC.munmap(address, PAGE) == 0, "munmap failed") @contextmanager def fresh(): fd = os.memfd_create("hesela-capability", 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(fcntl.fcntl(fd, fcntl.F_GET_SEALS) == EXEC_SEAL, "Unexpected initial seals") yield fd finally: os.close(fd) def readonly_descriptor(): with fresh() as fd: reader = os.open(f"/proc/self/fd/{fd}", os.O_RDONLY | os.O_CLOEXEC) try: require(fcntl.fcntl(reader, fcntl.F_GETFL) & os.O_ACCMODE == os.O_RDONLY, "Reader is not O_RDONLY") require((os.fstat(reader).st_dev, os.fstat(reader).st_ino) == (os.fstat(fd).st_dev, os.fstat(fd).st_ino), "Reader inode differs") with mapping(reader, READ) as address: check(fd, address) denied = expect_errno(lambda: protect(address, READ | WRITE), errno.EACCES) seal_denied = expect_errno(lambda: add(reader, fcntl.F_SEAL_WRITE), errno.EPERM) require(os.pwrite(fd, b"B", 0) == 1, "Writer did not change file") check(fd, address, b"B") add(fd, fcntl.F_SEAL_WRITE) require(fcntl.fcntl(reader, fcntl.F_GET_SEALS) == fcntl.fcntl(fd, fcntl.F_GET_SEALS), "Seal masks differ") blocked = expect_errno(lambda: os.pwrite(fd, b"C", 0), errno.EPERM) check(fd, address, b"B") return {"upgrade": denied, "seal_from_reader": seal_denied, "reader_after_other_fd_write": "B", "write_seal_while_reader_mapped": "installed", "write_after_seal": blocked, "final_file_byte": "B"} finally: os.close(reader) def before_future_seal(): with fresh() as fd: with mapping(fd, READ | WRITE) as address: check(fd, address) protect(address, READ) add(fd, FUTURE_WRITE) blocked = expect_errno(lambda: os.pwrite(fd, b"C", 0), errno.EPERM) check(fd, address) busy = expect_errno(lambda: add(fd, fcntl.F_SEAL_WRITE), errno.EBUSY) require(fcntl.fcntl(fd, fcntl.F_GET_SEALS) & fcntl.F_SEAL_WRITE == 0, "Rejected WRITE unexpectedly installed") protect(address, READ | WRITE) ctypes.memmove(address, b"B", 1) check(fd, address, b"B") add(fd, fcntl.F_SEAL_WRITE) require(os.pread(fd, PAGE + 1, 0) == payload(b"B"), "Final file payload mismatch") return {"downgrade": "succeeded", "pwrite_after_future_seal": blocked, "write_seal_while_readonly": busy, "upgrade_after_future_seal": "succeeded", "file_after_mapped_write": "B", "write_seal_after_unmap": "installed"} def after_future_seal(): with fresh() as fd: add(fd, FUTURE_WRITE) with mapping(fd, READ) as address: check(fd, address) denied = expect_errno(lambda: protect(address, READ | WRITE), errno.EACCES) check(fd, address) add(fd, fcntl.F_SEAL_WRITE) blocked = expect_errno(lambda: os.pwrite(fd, b"B", 0), errno.EPERM) check(fd, address) return {"upgrade_after_future_seal": denied, "write_seal_while_readonly": "installed", "write_after_seal": blocked, "final_file_byte": "A"} CASES = [readonly_descriptor, before_future_seal, after_future_seal] def run(repetitions=3): require(type(repetitions) is int and 1 <= repetitions <= 100, "Use 1 to 100 repetitions") require(platform.system() == "Linux" and ctypes.sizeof(ctypes.c_void_p) == 8, "This ctypes ABI probe requires 64-bit Linux") require(hasattr(os, "memfd_create"), "Python lacks memfd support") 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-mapping-capability", "generatedAt": datetime.now(timezone.utc).isoformat(), "sourceSha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "environment": {"kernel": platform.release(), "machine": platform.machine(), "python": platform.python_version(), "pageSizeBytes": PAGE, "pointerBits": ctypes.sizeof(ctypes.c_void_p) * 8, "initialSealMask": EXEC_SEAL}, "repetitions": repetitions, "casesPerRepetition": len(CASES), "observations": observations, "limits": ["Sequential single-process controls, no concurrent writer or descriptor transfer.", "No power loss, persistent media, performance, private mapping or pinned-page test.", "Fresh non-executable memfds only; procfs reopens this process's own descriptor."]} 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 stream: stream.write(result) else: print(result, end="") if __name__ == "__main__": main()