"""Run one submission inside an isolated, disposable directory. The grader and the self-check both run submissions this way. It encodes several grader-integrity defences; read the comments before changing anything. """ from __future__ import annotations import errno import os import pwd import shutil import stat import signal import subprocess import tempfile import time from pathlib import Path # The unprivileged account a method runs under. The grader refuses to start without it. SOLVER_ACCOUNT = "solver" # Size cap for submission output; check the size before reading. MAX_OUTPUT_BYTES = 64 * 1024 * 1024 # build.sh runs once per round, not per instance. BUILD_TIMEOUT_SEC = 900.0 # Env var carrying the per-instance wall-clock budget into run.sh (the run.sh # contract is two positional args, so the budget travels in the environment). BUDGET_ENV = "TASK_BUDGET_SEC" STATUSES = frozenset({"ok", "timeout", "run_failed", "stray_processes", "unreaped", "output_too_large", "output_not_regular_file"}) # The wall-clock seconds run.sh ran in the last _run call, from its start to its exit (or to the reap # after a timeout); None when it never started. A round scored by its time reads it through the # metric's {elapsed}: the caller hands it to package_common.ELAPSED. Every # _run call sets it afresh, so it never describes another instance's run. LAST_RUN_SEC: float | None = None # Only a whitelist of env vars reaches the untrusted submission; the budget is added on top. # CORE_DIR tells the method where the core's code is installed. ALLOWED_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "LC_CTYPE", "TZ", "TERM", "OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS", "CORE_DIR") def _child_env(**extra: str) -> dict: env = {k: os.environ[k] for k in ALLOWED_ENV if k in os.environ} env.update(extra) return env def solver_ids() -> tuple[int, int] | None: try: e = pwd.getpwnam(SOLVER_ACCOUNT) except KeyError: return None return e.pw_uid, e.pw_gid def _group_members(pgid: int) -> list[int]: """Read /proc, not killpg(pgid, 0): EPERM there proves the group exists, not that it is empty.""" members = [] for entry in os.listdir("/proc"): if not entry.isdigit(): continue try: with open(f"/proc/{entry}/stat", "rb") as f: fields = f.read().rsplit(b") ", 1)[1].split() except (OSError, IndexError): continue # Fields after comm: state ppid pgrp ... if len(fields) > 2 and fields[2] == str(pgid).encode(): members.append(int(entry)) return members def _reap_group(pgid: int) -> list[int]: """Kill the process group and wait; returns pids still alive (empty means clean).""" try: os.killpg(pgid, signal.SIGKILL) except ProcessLookupError: return [] except PermissionError: return _group_members(pgid) # cannot kill: report, do not swallow for _ in range(40): remaining = _group_members(pgid) if not remaining: return [] time.sleep(0.05) return _group_members(pgid) def _uid_processes(uid: int) -> list[int]: """Scan by uid, since setsid leaves the process group but cannot change uid.""" out = [] for entry in os.listdir("/proc"): if not entry.isdigit(): continue try: with open(f"/proc/{entry}/status", "rb") as f: for line in f: if line.startswith(b"Uid:"): if int(line.split()[1]) == uid: out.append(int(entry)) break except (OSError, IndexError, ValueError): continue return out def _reap_uid(uid: int) -> list[int]: """Kill every process owned by uid; returns pids still alive.""" if os.getuid() == uid: # Killing by uid would kill the grader itself. return [] me = os.getpid() for pid in _uid_processes(uid): if pid == me: continue try: os.kill(pid, signal.SIGKILL) except (ProcessLookupError, PermissionError): pass for _ in range(40): remaining = _uid_processes(uid) if not remaining: return [] time.sleep(0.05) return _uid_processes(uid) def _run(submission_dir: Path, data_dir: Path, out_dir: Path, work_dir: Path, budget_sec: float, solver: tuple[int, int] | None) -> str: """Returns ok / timeout / run_failed / stray_processes / unreaped.""" no_new_privs() _drop_set_id_bits(submission_dir) global LAST_RUN_SEC LAST_RUN_SEC = None # An executable run.sh runs by its shebang; without the executable bit, under /bin/sh. entry = submission_dir / "run.sh" cmd = ([str(entry)] if os.access(entry, os.X_OK) else ["/bin/sh", str(entry)]) + [str(data_dir), str(out_dir)] # The run.sh contract is fixed at two arguments, so the budget travels in the environment. env = _child_env(**{BUDGET_ENV: f"{budget_sec:.3f}"}) kwargs: dict = dict(cwd=str(work_dir), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, env=env) if solver is not None: # extra_groups=[]: otherwise the child keeps root's supplementary groups. kwargs["user"], kwargs["group"], kwargs["extra_groups"] = solver[0], solver[1], [] status = "ok" t0 = time.monotonic() try: proc = subprocess.Popen(cmd, **kwargs) except OSError: # no usable shebang, or not runnable if cmd[0] == "/bin/sh": return "run_failed" try: proc = subprocess.Popen(["/bin/sh", *cmd], **kwargs) except OSError: return "run_failed" pgid = os.getpgid(proc.pid) try: if proc.wait(timeout=budget_sec) != 0: status = "run_failed" except subprocess.TimeoutExpired: status = "timeout" _reap_group(pgid) proc.wait() LAST_RUN_SEC = round(time.monotonic() - t0, 3) # Check after timeouts too: forked background processes survive proc.wait(). leftovers = _group_members(pgid) if leftovers: still = _reap_group(pgid) if still: status = "unreaped" elif status == "ok": status = "stray_processes" # Second pass by uid: reap the group first, then catch whatever left it. if solver is not None and os.getuid() != solver[0]: left_group = _uid_processes(solver[0]) if left_group: still = _reap_uid(solver[0]) if still: status = "unreaped" elif status == "ok": status = "stray_processes" return status def _read_output(out_path: Path, instance_name: str) -> tuple[bytes | None, str | None]: """Read one file the submission wrote; returns (text, overriding status or None). O_NOFOLLOW: refuse a symlinked output, and fstat for a regular file, so the root-owned grader cannot be pointed at sealed data or an infinite device; size and read share one fd so the file cannot be swapped underneath. """ try: # O_NONBLOCK: opening a FIFO the submission left behind must not hang the grader. fd = os.open(out_path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) except FileNotFoundError: return None, None except OSError as e: if e.errno in (errno.ELOOP, errno.EMLINK): return None, "output_not_regular_file" raise RuntimeError( f"cannot open the output of {instance_name}: {type(e).__name__}: {e}") from e try: st = os.fstat(fd) if not stat.S_ISREG(st.st_mode): return None, "output_not_regular_file" if st.st_size > MAX_OUTPUT_BYTES: return None, "output_too_large" # Still read with a cap: st_size need not match what is readable. data = b"" while len(data) <= MAX_OUTPUT_BYTES: chunk = os.read(fd, 1 << 20) if not chunk: break data += chunk if len(data) > MAX_OUTPUT_BYTES: return None, "output_too_large" except OSError as e: raise RuntimeError( f"cannot read the output of {instance_name}: {type(e).__name__}: {e}") from e finally: os.close(fd) return data, None def stage_and_run(submission_dir: Path, data_dir: Path, outputs: tuple[str, ...], budget_sec: float, solver: tuple[int, int] | None): """Run the method once in a disposable staging dir; returns (status, {name: bytes or None}). Layout: /data holds the measurements the method may read (read-only), /work belongs to the solver and is where it writes its files. The directory names are constant so a method cannot tell from the path which instance it is working on. """ root = Path(tempfile.mkdtemp(prefix="run_")) try: staged, work = root / "data", root / "work" shutil.copytree(data_dir, staged) for path in staged.rglob("*"): path.chmod(0o444 if path.is_file() else 0o555) staged.chmod(0o555) work.mkdir() if solver is not None: os.chown(work, solver[0], solver[1]) work.chmod(0o700) else: work.chmod(0o755) root.chmod(0o755) status = _run(submission_dir, staged, work, work, budget_sec, solver) texts = {} for name in outputs: text, read_status = _read_output(work / name, name) texts[name] = text if read_status is not None: status = read_status return status, texts finally: # No ignore_errors: this dir holds a copy of the instance's inputs, which may be sealed, # so a failed cleanup is a leak and must be reported. try: shutil.rmtree(root) except OSError as e: raise RuntimeError( f"cannot clean up staging dir {root}: {type(e).__name__}: {e}") from e if root.exists(): raise RuntimeError(f"staging dir {root} still exists; measurements may leak") def build_submission(submission_dir: Path, solver) -> tuple[bool, str]: """Run the submission's build.sh once; returns (ok, note). No build.sh counts as success. stderr goes to a temp file rather than a pipe (a pipe waits for EOF, so a build.sh handing stdout to a background process would burn the whole budget); the whole process group is reaped, then uid as a backstop; and a failure to launch is infrastructure, so it raises instead of scoring the submission 0. """ no_new_privs() script = submission_dir / "build.sh" if not script.exists(): return True, "submission has no build.sh" # Build artifacts land in the submission dir, and the build runs unprivileged, # so the tree has to be handed over first or a compiler write fails with EACCES. if solver is not None: # Hand the tree to the unprivileged account. Walk without following # symlinks and refuse any link, so chown cannot cross into root-owned # sealed data; lchown double-guards. if submission_dir.is_symlink(): return False, "submission dir is a symlink" try: os.lchown(submission_dir, solver[0], solver[1]) for cur, dirs, files in os.walk(submission_dir): for name in dirs + files: p = os.path.join(cur, name) if os.path.islink(p): return False, f"submission contains a symlink: {name}" os.lchown(p, solver[0], solver[1]) except OSError as e: raise RuntimeError( f"cannot hand submission dir {submission_dir} to the unprivileged " f"account: {type(e).__name__}: {e}") from e with tempfile.TemporaryFile() as err: kwargs: dict = dict(cwd=str(submission_dir), stdout=subprocess.DEVNULL, stderr=err, start_new_session=True, env=_child_env()) if solver is not None: # extra_groups=[]: otherwise the child keeps root's supplementary groups. kwargs["user"], kwargs["group"], kwargs["extra_groups"] = solver[0], solver[1], [] try: proc = subprocess.Popen(["/bin/sh", str(script)], **kwargs) except OSError as e: raise RuntimeError( f"cannot execute {script}: {type(e).__name__}: {e}." " This is an infrastructure failure, not the submission's fault," " so the round is aborted rather than scored 0.") from e pgid = os.getpgid(proc.pid) timed_out = False try: rc = proc.wait(timeout=BUILD_TIMEOUT_SEC) except subprocess.TimeoutExpired: timed_out, rc = True, None _reap_group(pgid) proc.wait() left = _reap_group(pgid) # reap grandchildren even on a clean exit if solver is not None: # the process group cannot hold setsid; uid can left = left or _reap_uid(solver[0]) err.seek(0) tail = err.read()[-300:].decode(errors="replace") if timed_out: return False, f"build.sh did not finish within {BUILD_TIMEOUT_SEC:.0f} s" if left: return False, f"build.sh left unkillable processes {left}" if rc != 0: return False, f"build.sh exited with code {rc}: {tail}" return True, "build succeeded" # ---------------------------------------------------------------- set-id bits, dropped before a method's first run # A method's files run under the method's account: before the first run of a method directory, every set-id bit of a # regular file in it is dropped, once per directory and process, and no run starts until that is done. Owners and # permissions stay as they are. import os as _os import stat as _stat import threading as _threading _SET_ID_DONE: set = set() _SET_ID_GUARD = _threading.Lock() _SET_ID_BITS = _stat.S_ISUID | _stat.S_ISGID def _drop_set_id_bits(method) -> None: """Links are neither followed nor changed: each file is opened without following a link, and checked again.""" method = _os.path.realpath(method) with _SET_ID_GUARD: if method in _SET_ID_DONE: return for cur, _dirs, files in _os.walk(method): for name in files: p = _os.path.join(cur, name) st = _os.lstat(p) if not (_stat.S_ISREG(st.st_mode) and st.st_mode & _SET_ID_BITS): continue fd = _os.open(p, _os.O_RDONLY | _os.O_NOFOLLOW | _os.O_NONBLOCK) try: st = _os.fstat(fd) if _stat.S_ISREG(st.st_mode): _os.fchmod(fd, _stat.S_IMODE(st.st_mode) & ~_SET_ID_BITS) finally: _os.close(fd) _SET_ID_DONE.add(method) # ---------------------------------------------------------------- no new privileges, before build.sh and every run # prctl(2)'s PR_SET_NO_NEW_PRIVS. build.sh and every run start from a thread that has set it (no_new_privs), so # nothing they start gains privileges by exec: a set-id program, the method's or the image's, runs as their account. PR_SET_NO_NEW_PRIVS = 38 def no_new_privs() -> None: """Set PR_SET_NO_NEW_PRIVS on the calling thread, which every process it starts inherits; this process, root already where a submission takes an account, gains nothing by exec and so loses nothing. Raises RuntimeError where it cannot, since the submission could then gain privileges its account does not have.""" try: import ctypes libc = ctypes.CDLL(None, use_errno=True) if libc.prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == 0: return why = _os.strerror(ctypes.get_errno()) except (ImportError, OSError, AttributeError) as e: why = f"{type(e).__name__}: {e}" raise RuntimeError(f"cannot keep a submission from gaining privileges ({why}); stopping rather than run it")