File size: 15,825 Bytes
7f50cd1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | """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"})
# 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."""
# An executable run.sh runs by its shebang; without the executable bit, under /bin/sh.
no_new_privs()
_drop_set_id_bits(submission_dir)
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"
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()
# 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[str | 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.decode("utf-8", errors="replace"), 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: text or None}).
Layout: <root>/data holds the measurements the method may read (read-only), <root>/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")
|