Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/columbia/environment/candidate-abi/websitebench/__init__.py +1 -0
- tasks/columbia/environment/candidate-abi/websitebench/harbor/__init__.py +1 -0
- tasks/columbia/environment/candidate-abi/websitebench/harbor/candidate_preflight.py +179 -0
- tasks/columbia/environment/candidate-abi/websitebench/harbor/compiler.py +1128 -0
- tasks/columbia/environment/candidate-abi/websitebench/harbor/sandbox.py +841 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/0907-launch_UShomepageOG.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/10-27_COL_US_EFWtest2_HP_Storytelling_Card1.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/10-27_COL_US_EFWtest2_HP_Storytelling_Card2.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/10-27_COL_US_EFWtest2_HP_Storytelling_Card3.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/10-27_COL_US_EFWtest2_HP_Storytelling_Card5.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/10-27_COL_US_EFWtest2_HP_Storytelling_Hero.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/12-23_CGR_Logo.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2181437_C_NA_HP_StorytellingComponent_Card4_v4.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2279348_COL_US_Q1-Q2_SpringSummer_NewArrivals_Visnav_Infant.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2279348_COL_US_Q1-Q2_SpringSummer_NewArrivals_Visnav_Mens_Shirts.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2308014_CA_Jackets_Mens_VisNav_Slot04.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2308014_US_Supergrid_TopLevel_Equip_VisNav_Slot01.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2308014_US_Supergrid_TopLevel_Equip_VisNav_Slot02.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2308014_US_Supergrid_TopLevel_Equip_VisNav_Slot03.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2308014_US_Supergrid_TopLevel_Equip_VisNav_Slot04.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_ACE.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Bottoms.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Dresses.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Girls.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Jackets.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Shoes.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Tops.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_BigTall.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_Boys.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_K_Shoes.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_M_Shoes.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_MensACE.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_MensBottoms.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_MensShoes.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_Toddlers_v2.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_W_Shoes.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_NA_August_VisNavBanners_CampingGear.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_NA_August_VisNavBanners_Drinkware.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Beanie.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Belts.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Booney.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Gaiters.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Hats.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Socks.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/6-30_COL_US_S26_HP_SummerTech_M_Subhero.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/7-30_COL_CA_S26_HP_Run_Subhero.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/8-10_2686468_COL_US_HP_AmazeSweats_Subhero.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/8-10_2686468_COL_US_HP_FallNA_DG_Subhero.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/8-10_ROC_MomensBan_DG.webp +3 -0
- tasks/columbia/environment/reference/clone/static/assets/cms/8-27_COL_US_HP_We_Heart_AmazePuff_Style_Subhero_v2.webp +3 -0
tasks/columbia/environment/candidate-abi/websitebench/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Public WebsiteBench candidate ABI tooling."""
|
tasks/columbia/environment/candidate-abi/websitebench/harbor/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Public Harbor candidate ABI tooling."""
|
tasks/columbia/environment/candidate-abi/websitebench/harbor/candidate_preflight.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Agent-visible preflight for the public Harbor candidate runtime ABI."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import socket
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Sequence
|
| 12 |
+
|
| 13 |
+
from .compiler import (
|
| 14 |
+
CompilerSandboxError,
|
| 15 |
+
RuntimeInfrastructureError,
|
| 16 |
+
compile_candidate,
|
| 17 |
+
validate_runtime_lifecycle,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
FORBIDDEN_PRIVATE_ROOT = b"/app/repo"
|
| 22 |
+
NONPORTABLE_PYTHON_SHEBANG = b"#!/usr/bin/python3"
|
| 23 |
+
PORTABLE_PYTHON_SHEBANG = b"#!/usr/bin/env python3"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _first_line(path: Path) -> bytes:
|
| 27 |
+
with path.open("rb") as handle:
|
| 28 |
+
return handle.readline(4097).rstrip(b"\r\n")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _contains(path: Path, needle: bytes) -> bool:
|
| 32 |
+
overlap = max(0, len(needle) - 1)
|
| 33 |
+
previous = b""
|
| 34 |
+
with path.open("rb") as handle:
|
| 35 |
+
while chunk := handle.read(1024 * 1024):
|
| 36 |
+
value = previous + chunk
|
| 37 |
+
if needle in value:
|
| 38 |
+
return True
|
| 39 |
+
previous = value[-overlap:] if overlap else b""
|
| 40 |
+
return False
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def validate_portable_candidate_paths(
|
| 44 |
+
compile_script: Path, executable: Path | None = None
|
| 45 |
+
) -> None:
|
| 46 |
+
"""Reject paths that work in the Agent checkout but not the private build."""
|
| 47 |
+
|
| 48 |
+
if _contains(compile_script, FORBIDDEN_PRIVATE_ROOT):
|
| 49 |
+
raise CompilerSandboxError(
|
| 50 |
+
"compile.sh hard-codes /app/repo; the verifier relocates the candidate "
|
| 51 |
+
"to a private build root. Use paths relative to the current directory "
|
| 52 |
+
"or $WEBSITEBENCH_BUILD_ROOT."
|
| 53 |
+
)
|
| 54 |
+
if _first_line(compile_script) == NONPORTABLE_PYTHON_SHEBANG:
|
| 55 |
+
raise CompilerSandboxError(
|
| 56 |
+
"compile.sh uses the non-portable #!/usr/bin/python3 shebang; use "
|
| 57 |
+
"#!/usr/bin/env python3."
|
| 58 |
+
)
|
| 59 |
+
if executable is None:
|
| 60 |
+
return
|
| 61 |
+
if _first_line(executable) == NONPORTABLE_PYTHON_SHEBANG:
|
| 62 |
+
raise CompilerSandboxError(
|
| 63 |
+
"executable uses the non-portable #!/usr/bin/python3 shebang; use "
|
| 64 |
+
"#!/usr/bin/env python3."
|
| 65 |
+
)
|
| 66 |
+
if _contains(executable, FORBIDDEN_PRIVATE_ROOT):
|
| 67 |
+
raise CompilerSandboxError(
|
| 68 |
+
"executable contains /app/repo; runtime files live in the private "
|
| 69 |
+
"build root. Resolve resources relative to executable, not /app/repo."
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _free_port() -> int:
|
| 74 |
+
with socket.socket() as probe:
|
| 75 |
+
probe.bind(("127.0.0.1", 0))
|
| 76 |
+
return int(probe.getsockname()[1])
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _build_log(private_root: Path) -> str:
|
| 80 |
+
path = private_root / "build.log"
|
| 81 |
+
try:
|
| 82 |
+
value = path.read_text(encoding="utf-8", errors="replace")
|
| 83 |
+
except OSError:
|
| 84 |
+
return ""
|
| 85 |
+
return value[-65536:]
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def run_preflight(
|
| 89 |
+
candidate_root: Path,
|
| 90 |
+
*,
|
| 91 |
+
timeout: float = 300.0,
|
| 92 |
+
seed: int = 0,
|
| 93 |
+
timezone: str = "UTC",
|
| 94 |
+
) -> dict[str, object]:
|
| 95 |
+
candidate = candidate_root.resolve(strict=True)
|
| 96 |
+
compile_script = candidate / "compile.sh"
|
| 97 |
+
if not compile_script.is_file():
|
| 98 |
+
raise CompilerSandboxError("candidate root does not contain compile.sh")
|
| 99 |
+
validate_portable_candidate_paths(compile_script)
|
| 100 |
+
with tempfile.TemporaryDirectory(prefix="websitebench-candidate-preflight-") as raw:
|
| 101 |
+
working_root = Path(raw)
|
| 102 |
+
private_root = working_root / "compiler"
|
| 103 |
+
try:
|
| 104 |
+
artifact = compile_candidate(
|
| 105 |
+
candidate,
|
| 106 |
+
private_root,
|
| 107 |
+
timeout=timeout,
|
| 108 |
+
seed=seed,
|
| 109 |
+
timezone=timezone,
|
| 110 |
+
)
|
| 111 |
+
except CompilerSandboxError as exc:
|
| 112 |
+
log = _build_log(private_root)
|
| 113 |
+
if log:
|
| 114 |
+
raise CompilerSandboxError(f"{exc}\ncompiler output:\n{log}") from exc
|
| 115 |
+
raise
|
| 116 |
+
validate_portable_candidate_paths(
|
| 117 |
+
artifact.build_root / "compile.sh", artifact.executable
|
| 118 |
+
)
|
| 119 |
+
lifecycle = validate_runtime_lifecycle(
|
| 120 |
+
artifact,
|
| 121 |
+
port=_free_port(),
|
| 122 |
+
seed=seed,
|
| 123 |
+
working_root=working_root / "runtime-preflight",
|
| 124 |
+
worker_access_roots=(working_root,),
|
| 125 |
+
timezone=timezone,
|
| 126 |
+
)
|
| 127 |
+
if lifecycle.get("valid") is not True:
|
| 128 |
+
failed = sorted(
|
| 129 |
+
key
|
| 130 |
+
for key, value in lifecycle.items()
|
| 131 |
+
if key not in {"deployment_abi", "tree_sha256", "valid"}
|
| 132 |
+
and value is not True
|
| 133 |
+
)
|
| 134 |
+
raise CompilerSandboxError(
|
| 135 |
+
"candidate runtime ABI lifecycle failed: " + ",".join(failed)
|
| 136 |
+
)
|
| 137 |
+
return {
|
| 138 |
+
"schema": "websitebench.harbor.candidate-preflight",
|
| 139 |
+
"status": "valid",
|
| 140 |
+
"candidate_root": str(candidate),
|
| 141 |
+
"tree_sha256": artifact.tree_sha256,
|
| 142 |
+
"lifecycle": lifecycle,
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _parser() -> argparse.ArgumentParser:
|
| 147 |
+
parser = argparse.ArgumentParser(
|
| 148 |
+
description="Check a candidate with the formal private compile/runtime ABI."
|
| 149 |
+
)
|
| 150 |
+
parser.add_argument("candidate_root", nargs="?", type=Path, default=Path.cwd())
|
| 151 |
+
parser.add_argument("--timeout", type=float, default=300.0)
|
| 152 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 153 |
+
parser.add_argument("--timezone", default="UTC")
|
| 154 |
+
return parser
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def main(arguments: Sequence[str] | None = None) -> int:
|
| 158 |
+
values = _parser().parse_args(arguments)
|
| 159 |
+
try:
|
| 160 |
+
report = run_preflight(
|
| 161 |
+
values.candidate_root,
|
| 162 |
+
timeout=values.timeout,
|
| 163 |
+
seed=values.seed,
|
| 164 |
+
timezone=values.timezone,
|
| 165 |
+
)
|
| 166 |
+
except (
|
| 167 |
+
CompilerSandboxError,
|
| 168 |
+
RuntimeInfrastructureError,
|
| 169 |
+
OSError,
|
| 170 |
+
ValueError,
|
| 171 |
+
) as exc:
|
| 172 |
+
print(f"candidate ABI preflight failed: {exc}", file=sys.stderr)
|
| 173 |
+
return 2
|
| 174 |
+
print(json.dumps(report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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Quarantined compiler and runtime for the Harbor compile-executable ABI."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import ctypes
|
| 6 |
+
import errno
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import shutil
|
| 11 |
+
import signal
|
| 12 |
+
import stat
|
| 13 |
+
import subprocess
|
| 14 |
+
import time
|
| 15 |
+
import urllib.error
|
| 16 |
+
import urllib.request
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Iterable, Mapping, Sequence
|
| 20 |
+
|
| 21 |
+
try: # pragma: no cover - unavailable on Windows authoring hosts
|
| 22 |
+
import resource
|
| 23 |
+
except ImportError: # pragma: no cover
|
| 24 |
+
resource = None # type: ignore[assignment]
|
| 25 |
+
|
| 26 |
+
from . import sandbox
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
DEPLOYMENT_ABI = "websitebench.harbor.compile-executable"
|
| 30 |
+
COMPILE_ENTRYPOINT = "compile.sh"
|
| 31 |
+
EXECUTABLE_ENTRYPOINT = "executable"
|
| 32 |
+
HEALTH_PATH = "/healthz"
|
| 33 |
+
# The contract moved to /healthz (ADR-0010) because every reference site and
|
| 34 |
+
# every manifest already served that path, while nothing ever implemented the
|
| 35 |
+
# benchmark-private one. Candidates built against the old instruction text keep
|
| 36 |
+
# working: probing falls back to these.
|
| 37 |
+
LEGACY_HEALTH_PATHS = ("/__websitebench/health",)
|
| 38 |
+
HEALTH_PATHS = (HEALTH_PATH, *LEGACY_HEALTH_PATHS)
|
| 39 |
+
HEALTH_BODY = {"status": "ok"}
|
| 40 |
+
RUNTIME_PROCESS_MODEL = {
|
| 41 |
+
"kind": "single-process",
|
| 42 |
+
"process_fork": False,
|
| 43 |
+
"threads": True,
|
| 44 |
+
"launcher": "direct-exec-or-shell-builtins-only",
|
| 45 |
+
}
|
| 46 |
+
DEFAULT_COMPILE_TIMEOUT = 900.0
|
| 47 |
+
MAX_LOG_BYTES = 256 * 1024 * 1024
|
| 48 |
+
WORKER_OS_UID = 10001
|
| 49 |
+
WORKER_OS_GID = 10001
|
| 50 |
+
_RUNTIME_PRIVATE_DIRECTORIES = (
|
| 51 |
+
"home",
|
| 52 |
+
"tmp",
|
| 53 |
+
"xdg-cache",
|
| 54 |
+
"xdg-config",
|
| 55 |
+
"xdg-data",
|
| 56 |
+
)
|
| 57 |
+
CANDIDATE_MAIL_ENVIRONMENT = frozenset(
|
| 58 |
+
{
|
| 59 |
+
"WEBSITEBENCH_MAIL_API_URL",
|
| 60 |
+
"WEBSITEBENCH_MAIL_API_TOKEN",
|
| 61 |
+
"WEBSITEBENCH_MAIL_FROM",
|
| 62 |
+
"WEBSITEBENCH_SMTP_HOST",
|
| 63 |
+
"WEBSITEBENCH_SMTP_PORT",
|
| 64 |
+
"WEBSITEBENCH_SMTP_FROM",
|
| 65 |
+
"WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL",
|
| 66 |
+
"WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN",
|
| 67 |
+
}
|
| 68 |
+
)
|
| 69 |
+
CANDIDATE_EVALUATOR_ENVIRONMENT = frozenset(
|
| 70 |
+
{
|
| 71 |
+
"WEBSITEBENCH_VERIFIER_MODE",
|
| 72 |
+
"WEBSITEBENCH_VERIFIER_ALEX_SECRET",
|
| 73 |
+
"WEBSITEBENCH_VERIFIER_JORDAN_SECRET",
|
| 74 |
+
"WEBSITEBENCH_EVALUATOR_PRIMARY_SECRET",
|
| 75 |
+
"WEBSITEBENCH_EVALUATOR_SECONDARY_SECRET",
|
| 76 |
+
}
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class CompilerSandboxError(RuntimeError):
|
| 81 |
+
"""The candidate artifact, compiler, or compiled runtime broke the ABI."""
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class RuntimeInfrastructureError(RuntimeError):
|
| 85 |
+
"""The trusted runtime supervisor could not establish its worker boundary."""
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _runtime_worker_credentials() -> tuple[int, int] | None:
|
| 89 |
+
"""Return the fixed worker identity only for a privileged supervisor."""
|
| 90 |
+
|
| 91 |
+
if os.geteuid() == 0:
|
| 92 |
+
return WORKER_OS_UID, WORKER_OS_GID
|
| 93 |
+
return None
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _worker_execute_bit(metadata: os.stat_result, uid: int, gid: int) -> int:
|
| 97 |
+
if metadata.st_uid == uid:
|
| 98 |
+
return stat.S_IXUSR
|
| 99 |
+
if metadata.st_gid == gid:
|
| 100 |
+
return stat.S_IXGRP
|
| 101 |
+
return stat.S_IXOTH
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _worker_access_root(path: Path, roots: Sequence[Path]) -> Path:
|
| 105 |
+
matches = [root for root in roots if path == root or root in path.parents]
|
| 106 |
+
if not matches:
|
| 107 |
+
raise OSError(
|
| 108 |
+
errno.EPERM,
|
| 109 |
+
f"worker path is outside caller-declared access roots: {path}",
|
| 110 |
+
)
|
| 111 |
+
return max(matches, key=lambda root: len(root.parts))
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _make_worker_ancestors_traversable(
|
| 115 |
+
path: Path,
|
| 116 |
+
uid: int,
|
| 117 |
+
gid: int,
|
| 118 |
+
*,
|
| 119 |
+
access_root: Path,
|
| 120 |
+
) -> None:
|
| 121 |
+
"""Grant traverse only within one exact caller-declared task root."""
|
| 122 |
+
|
| 123 |
+
for boundary_parent in access_root.parents:
|
| 124 |
+
metadata = boundary_parent.stat()
|
| 125 |
+
if not stat.S_ISDIR(metadata.st_mode) or not (
|
| 126 |
+
stat.S_IMODE(metadata.st_mode)
|
| 127 |
+
& _worker_execute_bit(metadata, uid, gid)
|
| 128 |
+
):
|
| 129 |
+
raise OSError(
|
| 130 |
+
errno.EACCES,
|
| 131 |
+
f"worker access-root boundary is not traversable: {boundary_parent}",
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
ancestors = [path, *path.parents]
|
| 135 |
+
try:
|
| 136 |
+
boundary_index = ancestors.index(access_root)
|
| 137 |
+
except ValueError as exc: # guarded by _worker_access_root
|
| 138 |
+
raise OSError(errno.EPERM, "worker access-root containment changed") from exc
|
| 139 |
+
for ancestor in ancestors[: boundary_index + 1]:
|
| 140 |
+
metadata = ancestor.stat()
|
| 141 |
+
if not stat.S_ISDIR(metadata.st_mode):
|
| 142 |
+
raise OSError(errno.ENOTDIR, f"worker ancestor is not a directory: {ancestor}")
|
| 143 |
+
mode = stat.S_IMODE(metadata.st_mode)
|
| 144 |
+
execute_bit = _worker_execute_bit(metadata, uid, gid)
|
| 145 |
+
if not mode & execute_bit:
|
| 146 |
+
ancestor.chmod(mode | execute_bit)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _prepare_runtime_directories(
|
| 150 |
+
build: Path,
|
| 151 |
+
data: Path,
|
| 152 |
+
credentials: tuple[int, int] | None,
|
| 153 |
+
*,
|
| 154 |
+
worker_access_roots: Sequence[Path],
|
| 155 |
+
) -> None:
|
| 156 |
+
"""Create private runtime state and make it usable by the worker identity."""
|
| 157 |
+
|
| 158 |
+
data.mkdir(parents=True, exist_ok=True, mode=0o700)
|
| 159 |
+
private_directories = [data]
|
| 160 |
+
for name in _RUNTIME_PRIVATE_DIRECTORIES:
|
| 161 |
+
directory = data / name
|
| 162 |
+
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
| 163 |
+
private_directories.append(directory)
|
| 164 |
+
|
| 165 |
+
for directory in private_directories:
|
| 166 |
+
metadata = directory.lstat()
|
| 167 |
+
if not stat.S_ISDIR(metadata.st_mode):
|
| 168 |
+
raise OSError(
|
| 169 |
+
errno.ENOTDIR,
|
| 170 |
+
f"runtime private path is not a directory: {directory}",
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
if credentials is not None:
|
| 174 |
+
uid, gid = credentials
|
| 175 |
+
roots: list[Path] = []
|
| 176 |
+
for raw_root in worker_access_roots:
|
| 177 |
+
absolute = Path(raw_root).absolute()
|
| 178 |
+
root = absolute.resolve(strict=True)
|
| 179 |
+
metadata = absolute.lstat()
|
| 180 |
+
if (
|
| 181 |
+
root == Path(root.anchor)
|
| 182 |
+
or root != absolute
|
| 183 |
+
or not stat.S_ISDIR(metadata.st_mode)
|
| 184 |
+
):
|
| 185 |
+
raise OSError(errno.EPERM, f"invalid worker access root: {raw_root}")
|
| 186 |
+
if root not in roots:
|
| 187 |
+
roots.append(root)
|
| 188 |
+
if not roots:
|
| 189 |
+
raise OSError(errno.EPERM, "worker access roots were not declared")
|
| 190 |
+
for directory in private_directories:
|
| 191 |
+
os.chown(directory, uid, gid, follow_symlinks=False)
|
| 192 |
+
for target in (build, data):
|
| 193 |
+
access_root = _worker_access_root(target, roots)
|
| 194 |
+
_make_worker_ancestors_traversable(
|
| 195 |
+
target,
|
| 196 |
+
uid,
|
| 197 |
+
gid,
|
| 198 |
+
access_root=access_root,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
for directory in private_directories:
|
| 202 |
+
directory.chmod(0o700)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _proc_status_identity(path: Path) -> tuple[tuple[int, ...], tuple[int, ...], int]:
|
| 206 |
+
"""Read real/effective/saved/fs IDs and PPid from a proc status file."""
|
| 207 |
+
|
| 208 |
+
fields: dict[str, tuple[int, ...]] = {}
|
| 209 |
+
try:
|
| 210 |
+
for line in path.read_text(encoding="ascii").splitlines():
|
| 211 |
+
name, separator, value = line.partition(":")
|
| 212 |
+
if separator and name in {"Uid", "Gid", "PPid"}:
|
| 213 |
+
fields[name] = tuple(int(item) for item in value.split())
|
| 214 |
+
except (OSError, UnicodeError, ValueError) as exc:
|
| 215 |
+
raise OSError(errno.EIO, f"process identity is unreadable: {path}") from exc
|
| 216 |
+
if len(fields.get("Uid", ())) != 4 or len(fields.get("Gid", ())) != 4:
|
| 217 |
+
raise OSError(errno.EIO, f"process identity is incomplete: {path}")
|
| 218 |
+
if len(fields.get("PPid", ())) != 1:
|
| 219 |
+
raise OSError(errno.EIO, f"process parent identity is incomplete: {path}")
|
| 220 |
+
return fields["Uid"], fields["Gid"], fields["PPid"][0]
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
@dataclass(frozen=True)
|
| 224 |
+
class CompiledArtifact:
|
| 225 |
+
source_root: Path
|
| 226 |
+
build_root: Path
|
| 227 |
+
executable: Path
|
| 228 |
+
tree_sha256: str
|
| 229 |
+
build_log: Path
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _safe_name(name: str) -> bool:
|
| 233 |
+
return (
|
| 234 |
+
bool(name)
|
| 235 |
+
and name not in {".", ".."}
|
| 236 |
+
and "/" not in name
|
| 237 |
+
and "\x00" not in name
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _tree_entries(root: Path) -> Iterable[tuple[Path, os.stat_result]]:
|
| 242 |
+
"""Walk with lstat only; never follow candidate-authored links."""
|
| 243 |
+
|
| 244 |
+
stack = [root]
|
| 245 |
+
while stack:
|
| 246 |
+
directory = stack.pop()
|
| 247 |
+
with os.scandir(directory) as iterator:
|
| 248 |
+
entries = sorted(iterator, key=lambda item: os.fsencode(item.name))
|
| 249 |
+
subdirectories: list[Path] = []
|
| 250 |
+
for entry in entries:
|
| 251 |
+
if not _safe_name(entry.name):
|
| 252 |
+
raise CompilerSandboxError(f"unsafe artifact name: {entry.name!r}")
|
| 253 |
+
path = Path(entry.path)
|
| 254 |
+
metadata = entry.stat(follow_symlinks=False)
|
| 255 |
+
yield path, metadata
|
| 256 |
+
if stat.S_ISDIR(metadata.st_mode):
|
| 257 |
+
subdirectories.append(path)
|
| 258 |
+
stack.extend(reversed(subdirectories))
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def validate_artifact_tree(root: Path | str) -> list[Path]:
|
| 262 |
+
"""Reject links, special files, multiple links, and paths outside ``root``."""
|
| 263 |
+
|
| 264 |
+
resolved = Path(root).resolve(strict=True)
|
| 265 |
+
root_stat = resolved.lstat()
|
| 266 |
+
if not stat.S_ISDIR(root_stat.st_mode):
|
| 267 |
+
raise CompilerSandboxError("candidate artifact root must be a directory")
|
| 268 |
+
files: list[Path] = []
|
| 269 |
+
for path, metadata in _tree_entries(resolved):
|
| 270 |
+
try:
|
| 271 |
+
relative = path.relative_to(resolved)
|
| 272 |
+
except ValueError as exc: # defensive: scandir paths must remain below root
|
| 273 |
+
raise CompilerSandboxError(f"artifact path escapes root: {path}") from exc
|
| 274 |
+
if not relative.parts or any(
|
| 275 |
+
part in {"", ".", ".."} for part in relative.parts
|
| 276 |
+
):
|
| 277 |
+
raise CompilerSandboxError(f"unsafe artifact path: {relative}")
|
| 278 |
+
if stat.S_ISLNK(metadata.st_mode):
|
| 279 |
+
raise CompilerSandboxError(f"symbolic links are forbidden: {relative}")
|
| 280 |
+
if stat.S_ISREG(metadata.st_mode):
|
| 281 |
+
if metadata.st_nlink != 1:
|
| 282 |
+
raise CompilerSandboxError(
|
| 283 |
+
f"hard-linked files are forbidden: {relative}"
|
| 284 |
+
)
|
| 285 |
+
files.append(path)
|
| 286 |
+
elif not stat.S_ISDIR(metadata.st_mode):
|
| 287 |
+
raise CompilerSandboxError(f"special files are forbidden: {relative}")
|
| 288 |
+
return files
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def quarantine_artifact(source: Path | str, destination: Path | str) -> Path:
|
| 292 |
+
"""Copy `/app/repo` into a fresh private build root without link semantics."""
|
| 293 |
+
|
| 294 |
+
source_root = Path(source).resolve(strict=True)
|
| 295 |
+
destination_root = Path(destination).resolve()
|
| 296 |
+
validate_artifact_tree(source_root)
|
| 297 |
+
if destination_root.exists():
|
| 298 |
+
raise FileExistsError(f"private build root already exists: {destination_root}")
|
| 299 |
+
destination_root.mkdir(parents=True, mode=0o700)
|
| 300 |
+
try:
|
| 301 |
+
for path, metadata in _tree_entries(source_root):
|
| 302 |
+
relative = path.relative_to(source_root)
|
| 303 |
+
target = destination_root / relative
|
| 304 |
+
if stat.S_ISDIR(metadata.st_mode):
|
| 305 |
+
target.mkdir(mode=stat.S_IMODE(metadata.st_mode) | 0o700)
|
| 306 |
+
else:
|
| 307 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 308 |
+
with (
|
| 309 |
+
path.open("rb") as source_handle,
|
| 310 |
+
target.open("xb") as target_handle,
|
| 311 |
+
):
|
| 312 |
+
shutil.copyfileobj(source_handle, target_handle, length=1024 * 1024)
|
| 313 |
+
target_handle.flush()
|
| 314 |
+
os.fsync(target_handle.fileno())
|
| 315 |
+
target.chmod(stat.S_IMODE(metadata.st_mode))
|
| 316 |
+
validate_artifact_tree(destination_root)
|
| 317 |
+
except BaseException:
|
| 318 |
+
shutil.rmtree(destination_root, ignore_errors=True)
|
| 319 |
+
raise
|
| 320 |
+
return destination_root
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def _compile_environment(
|
| 324 |
+
build_root: Path, data_root: Path, seed: int, timezone: str
|
| 325 |
+
) -> dict[str, str]:
|
| 326 |
+
# This is an allowlist, not a copy of the verifier environment. In
|
| 327 |
+
# particular no provider, cloud, source, or hidden-fixture credential can
|
| 328 |
+
# reach compile.sh.
|
| 329 |
+
return {
|
| 330 |
+
"PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
|
| 331 |
+
"LANG": "C.UTF-8",
|
| 332 |
+
"LC_ALL": "C.UTF-8",
|
| 333 |
+
"HOST": "127.0.0.1",
|
| 334 |
+
"PORT": "3000",
|
| 335 |
+
"DATA_DIR": str(data_root),
|
| 336 |
+
"SEED": str(seed),
|
| 337 |
+
"TZ": timezone,
|
| 338 |
+
"HOME": str(data_root / "home"),
|
| 339 |
+
"TMPDIR": str(data_root / "tmp"),
|
| 340 |
+
"XDG_CACHE_HOME": str(data_root / "xdg-cache"),
|
| 341 |
+
"XDG_CONFIG_HOME": str(data_root / "xdg-config"),
|
| 342 |
+
"XDG_DATA_HOME": str(data_root / "xdg-data"),
|
| 343 |
+
"WEBSITEBENCH_DEPLOYMENT_ABI": DEPLOYMENT_ABI,
|
| 344 |
+
"WEBSITEBENCH_BUILD_ROOT": str(build_root),
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def _install_socket_deny_filter() -> None:
|
| 349 |
+
"""Deny sockets and process-group escape while allowing compiler children."""
|
| 350 |
+
|
| 351 |
+
(
|
| 352 |
+
audit_arch,
|
| 353 |
+
socket_syscall,
|
| 354 |
+
_fcntl_syscall,
|
| 355 |
+
seccomp_syscall,
|
| 356 |
+
_denied,
|
| 357 |
+
) = sandbox._architecture()
|
| 358 |
+
escape_syscalls = (109, 112) if audit_arch == 0xC000003E else (154, 157)
|
| 359 |
+
instructions = [
|
| 360 |
+
(sandbox.BPF_LD_W_ABS, 0, 0, 4),
|
| 361 |
+
(sandbox.BPF_JMP_JEQ_K, 1, 0, audit_arch),
|
| 362 |
+
(sandbox.BPF_RET_K, 0, 0, sandbox.SECCOMP_RET_KILL_PROCESS),
|
| 363 |
+
(sandbox.BPF_LD_W_ABS, 0, 0, 0),
|
| 364 |
+
(sandbox.BPF_JMP_JEQ_K, 0, 1, socket_syscall),
|
| 365 |
+
(
|
| 366 |
+
sandbox.BPF_RET_K,
|
| 367 |
+
0,
|
| 368 |
+
0,
|
| 369 |
+
sandbox.SECCOMP_RET_ERRNO | errno.EPERM,
|
| 370 |
+
),
|
| 371 |
+
]
|
| 372 |
+
for syscall_number in escape_syscalls:
|
| 373 |
+
instructions.extend(
|
| 374 |
+
[
|
| 375 |
+
(sandbox.BPF_JMP_JEQ_K, 0, 1, syscall_number),
|
| 376 |
+
(
|
| 377 |
+
sandbox.BPF_RET_K,
|
| 378 |
+
0,
|
| 379 |
+
0,
|
| 380 |
+
sandbox.SECCOMP_RET_ERRNO | errno.EPERM,
|
| 381 |
+
),
|
| 382 |
+
]
|
| 383 |
+
)
|
| 384 |
+
instructions.append((sandbox.BPF_RET_K, 0, 0, sandbox.SECCOMP_RET_ALLOW))
|
| 385 |
+
filters = (sandbox._SockFilter * len(instructions))(
|
| 386 |
+
*(sandbox._SockFilter(*instruction) for instruction in instructions)
|
| 387 |
+
)
|
| 388 |
+
program = sandbox._SockFprog(len(instructions), filters)
|
| 389 |
+
libc = ctypes.CDLL(None, use_errno=True)
|
| 390 |
+
if libc.prctl(sandbox.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
|
| 391 |
+
raise OSError(ctypes.get_errno(), "cannot set compiler no_new_privs")
|
| 392 |
+
result = int(
|
| 393 |
+
libc.syscall(
|
| 394 |
+
seccomp_syscall,
|
| 395 |
+
sandbox.SECCOMP_SET_MODE_FILTER,
|
| 396 |
+
0,
|
| 397 |
+
ctypes.byref(program),
|
| 398 |
+
)
|
| 399 |
+
)
|
| 400 |
+
if result != 0:
|
| 401 |
+
raise OSError(ctypes.get_errno(), "cannot install compiler network filter")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _compiler_preexec(
|
| 405 |
+
build_root: Path, data_root: Path, memory_mb: int, cpu_seconds: int
|
| 406 |
+
) -> None:
|
| 407 |
+
os.umask(0o077)
|
| 408 |
+
if resource is not None:
|
| 409 |
+
memory = memory_mb * 1024 * 1024
|
| 410 |
+
resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
|
| 411 |
+
resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds + 5))
|
| 412 |
+
resource.setrlimit(resource.RLIMIT_NOFILE, (1024, 1024))
|
| 413 |
+
resource.setrlimit(resource.RLIMIT_FSIZE, (MAX_LOG_BYTES, MAX_LOG_BYTES))
|
| 414 |
+
# Root and data are deliberately the same writable private tree for
|
| 415 |
+
# compilation. Landlock grants system toolchains read/execute access and
|
| 416 |
+
# grants no TCP bind/connect ports. It also withholds shared filesystem
|
| 417 |
+
# socket locations such as /run and /tmp.
|
| 418 |
+
sandbox._landlock(build_root, data_root, 1, set())
|
| 419 |
+
_install_socket_deny_filter()
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def _process_group_alive(group: int) -> bool:
|
| 423 |
+
proc = Path("/proc")
|
| 424 |
+
if proc.is_dir():
|
| 425 |
+
for status_path in proc.glob("[0-9]*/stat"):
|
| 426 |
+
try:
|
| 427 |
+
raw = status_path.read_text(encoding="ascii")
|
| 428 |
+
fields = raw[raw.rfind(")") + 2 :].split()
|
| 429 |
+
if int(fields[2]) == group and fields[0] != "Z":
|
| 430 |
+
return True
|
| 431 |
+
except (OSError, UnicodeError, ValueError, IndexError):
|
| 432 |
+
continue
|
| 433 |
+
return False
|
| 434 |
+
try:
|
| 435 |
+
os.killpg(group, 0)
|
| 436 |
+
except (ProcessLookupError, PermissionError):
|
| 437 |
+
return False
|
| 438 |
+
return True
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def _terminate_group(
|
| 442 |
+
process: subprocess.Popen[Any],
|
| 443 |
+
timeout: float = 10.0,
|
| 444 |
+
*,
|
| 445 |
+
accept_forced: bool = False,
|
| 446 |
+
) -> bool:
|
| 447 |
+
group = process.pid
|
| 448 |
+
if process.poll() is None:
|
| 449 |
+
try:
|
| 450 |
+
os.killpg(group, signal.SIGTERM)
|
| 451 |
+
except ProcessLookupError:
|
| 452 |
+
pass
|
| 453 |
+
deadline = time.monotonic() + timeout
|
| 454 |
+
while _process_group_alive(group) and time.monotonic() < deadline:
|
| 455 |
+
time.sleep(0.02)
|
| 456 |
+
graceful = not _process_group_alive(group)
|
| 457 |
+
if not graceful:
|
| 458 |
+
try:
|
| 459 |
+
os.killpg(group, signal.SIGKILL)
|
| 460 |
+
except ProcessLookupError:
|
| 461 |
+
pass
|
| 462 |
+
try:
|
| 463 |
+
process.wait(timeout=5)
|
| 464 |
+
except subprocess.TimeoutExpired:
|
| 465 |
+
return False
|
| 466 |
+
terminated = not _process_group_alive(group)
|
| 467 |
+
return graceful or (accept_forced and terminated)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def _stop_controlled_group(
|
| 471 |
+
process: subprocess.Popen[Any],
|
| 472 |
+
control_fd: int,
|
| 473 |
+
timeout: float = 10.0,
|
| 474 |
+
*,
|
| 475 |
+
accept_forced: bool = False,
|
| 476 |
+
) -> bool:
|
| 477 |
+
"""Ask the trusted sandbox launcher to stop its tracee, then reap the group."""
|
| 478 |
+
|
| 479 |
+
if process.poll() is None:
|
| 480 |
+
try:
|
| 481 |
+
os.write(control_fd, b"T")
|
| 482 |
+
except OSError:
|
| 483 |
+
pass
|
| 484 |
+
deadline = time.monotonic() + timeout
|
| 485 |
+
while _process_group_alive(process.pid) and time.monotonic() < deadline:
|
| 486 |
+
time.sleep(0.02)
|
| 487 |
+
graceful = not _process_group_alive(process.pid)
|
| 488 |
+
if not graceful:
|
| 489 |
+
try:
|
| 490 |
+
os.write(control_fd, b"K")
|
| 491 |
+
except OSError:
|
| 492 |
+
pass
|
| 493 |
+
time.sleep(0.1)
|
| 494 |
+
if _process_group_alive(process.pid):
|
| 495 |
+
try:
|
| 496 |
+
os.killpg(process.pid, signal.SIGKILL)
|
| 497 |
+
except ProcessLookupError:
|
| 498 |
+
pass
|
| 499 |
+
try:
|
| 500 |
+
process.wait(timeout=5)
|
| 501 |
+
except subprocess.TimeoutExpired:
|
| 502 |
+
return False
|
| 503 |
+
terminated = not _process_group_alive(process.pid)
|
| 504 |
+
return graceful or (accept_forced and terminated)
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def _processes_referencing(root: Path, *, exclude: Sequence[int] = ()) -> list[int]:
|
| 508 |
+
references: list[int] = []
|
| 509 |
+
root_text = str(root.resolve())
|
| 510 |
+
excluded = set(exclude)
|
| 511 |
+
for process in Path("/proc").glob("[0-9]*"):
|
| 512 |
+
try:
|
| 513 |
+
pid = int(process.name)
|
| 514 |
+
if pid in excluded:
|
| 515 |
+
continue
|
| 516 |
+
cwd = os.readlink(process / "cwd")
|
| 517 |
+
command = (
|
| 518 |
+
(process / "cmdline")
|
| 519 |
+
.read_bytes()
|
| 520 |
+
.replace(b"\x00", b" ")
|
| 521 |
+
.decode("utf-8", errors="replace")
|
| 522 |
+
)
|
| 523 |
+
except (OSError, ValueError):
|
| 524 |
+
continue
|
| 525 |
+
if (
|
| 526 |
+
cwd == root_text
|
| 527 |
+
or cwd.startswith(root_text + os.sep)
|
| 528 |
+
or root_text in command
|
| 529 |
+
):
|
| 530 |
+
references.append(pid)
|
| 531 |
+
return sorted(references)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def tree_digest(root: Path | str) -> str:
|
| 535 |
+
resolved = Path(root).resolve(strict=True)
|
| 536 |
+
validate_artifact_tree(resolved)
|
| 537 |
+
digest = hashlib.sha256()
|
| 538 |
+
for path, metadata in _tree_entries(resolved):
|
| 539 |
+
relative = path.relative_to(resolved).as_posix().encode("utf-8")
|
| 540 |
+
kind = b"d" if stat.S_ISDIR(metadata.st_mode) else b"f"
|
| 541 |
+
digest.update(kind + b"\0" + relative + b"\0")
|
| 542 |
+
digest.update(f"{stat.S_IMODE(metadata.st_mode):04o}".encode("ascii") + b"\0")
|
| 543 |
+
if kind == b"f":
|
| 544 |
+
with path.open("rb") as handle:
|
| 545 |
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
| 546 |
+
digest.update(chunk)
|
| 547 |
+
digest.update(b"\0")
|
| 548 |
+
return digest.hexdigest()
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def freeze_build_tree(root: Path | str) -> str:
|
| 552 |
+
resolved = Path(root).resolve(strict=True)
|
| 553 |
+
validate_artifact_tree(resolved)
|
| 554 |
+
entries = list(_tree_entries(resolved))
|
| 555 |
+
for path, metadata in entries:
|
| 556 |
+
if stat.S_ISREG(metadata.st_mode):
|
| 557 |
+
executable = bool(stat.S_IMODE(metadata.st_mode) & 0o111)
|
| 558 |
+
path.chmod(0o555 if executable else 0o444)
|
| 559 |
+
for path, metadata in reversed(entries):
|
| 560 |
+
if stat.S_ISDIR(metadata.st_mode):
|
| 561 |
+
path.chmod(0o555)
|
| 562 |
+
resolved.chmod(0o555)
|
| 563 |
+
return tree_digest(resolved)
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def compile_candidate(
|
| 567 |
+
source_root: Path | str,
|
| 568 |
+
private_root: Path | str,
|
| 569 |
+
*,
|
| 570 |
+
timeout: float = DEFAULT_COMPILE_TIMEOUT,
|
| 571 |
+
seed: int = 0,
|
| 572 |
+
timezone: str = "UTC",
|
| 573 |
+
memory_mb: int = 8192,
|
| 574 |
+
) -> CompiledArtifact:
|
| 575 |
+
"""Quarantine, compile offline once, validate, freeze, and hash the build."""
|
| 576 |
+
|
| 577 |
+
source = Path(source_root).resolve(strict=True)
|
| 578 |
+
private = Path(private_root).resolve()
|
| 579 |
+
if private.exists():
|
| 580 |
+
raise FileExistsError(f"private compiler root already exists: {private}")
|
| 581 |
+
private.mkdir(parents=True, mode=0o700)
|
| 582 |
+
build = private / "build"
|
| 583 |
+
log = private / "build.log"
|
| 584 |
+
quarantine_artifact(source, build)
|
| 585 |
+
data = build / ".websitebench-compile-data"
|
| 586 |
+
if data.exists():
|
| 587 |
+
if data.is_dir() and not data.is_symlink():
|
| 588 |
+
shutil.rmtree(data)
|
| 589 |
+
else:
|
| 590 |
+
data.unlink()
|
| 591 |
+
data.mkdir(mode=0o700)
|
| 592 |
+
for name in ("home", "tmp", "xdg-cache", "xdg-config", "xdg-data"):
|
| 593 |
+
(data / name).mkdir(mode=0o700)
|
| 594 |
+
compile_script = build / COMPILE_ENTRYPOINT
|
| 595 |
+
if not compile_script.is_file() or compile_script.is_symlink():
|
| 596 |
+
raise CompilerSandboxError("candidate root must contain regular compile.sh")
|
| 597 |
+
if compile_script.stat().st_nlink != 1 or not os.access(compile_script, os.X_OK):
|
| 598 |
+
raise CompilerSandboxError("compile.sh must be an independent executable file")
|
| 599 |
+
|
| 600 |
+
# A submitted executable is never trusted as compiler output.
|
| 601 |
+
preexisting = build / EXECUTABLE_ENTRYPOINT
|
| 602 |
+
if preexisting.exists():
|
| 603 |
+
if preexisting.is_dir():
|
| 604 |
+
shutil.rmtree(preexisting)
|
| 605 |
+
else:
|
| 606 |
+
preexisting.unlink()
|
| 607 |
+
|
| 608 |
+
environment = _compile_environment(build, data, seed, timezone)
|
| 609 |
+
with log.open("wb") as log_handle:
|
| 610 |
+
try:
|
| 611 |
+
process = subprocess.Popen(
|
| 612 |
+
[str(compile_script)],
|
| 613 |
+
cwd=build,
|
| 614 |
+
env=environment,
|
| 615 |
+
stdin=subprocess.DEVNULL,
|
| 616 |
+
stdout=log_handle,
|
| 617 |
+
stderr=subprocess.STDOUT,
|
| 618 |
+
start_new_session=True,
|
| 619 |
+
preexec_fn=lambda: _compiler_preexec(
|
| 620 |
+
build, build, memory_mb, max(1, int(timeout))
|
| 621 |
+
),
|
| 622 |
+
)
|
| 623 |
+
try:
|
| 624 |
+
return_code = process.wait(timeout=timeout)
|
| 625 |
+
except subprocess.TimeoutExpired as exc:
|
| 626 |
+
_terminate_group(process)
|
| 627 |
+
raise CompilerSandboxError(
|
| 628 |
+
f"compile.sh exceeded {timeout:g} seconds"
|
| 629 |
+
) from exc
|
| 630 |
+
if _process_group_alive(process.pid):
|
| 631 |
+
_terminate_group(process)
|
| 632 |
+
raise CompilerSandboxError(
|
| 633 |
+
"compile.sh left a child process or listener alive"
|
| 634 |
+
)
|
| 635 |
+
if return_code != 0:
|
| 636 |
+
raise CompilerSandboxError(f"compile.sh exited {return_code}")
|
| 637 |
+
finally:
|
| 638 |
+
log_handle.flush()
|
| 639 |
+
os.fsync(log_handle.fileno())
|
| 640 |
+
|
| 641 |
+
leaked = _processes_referencing(build, exclude=(os.getpid(),))
|
| 642 |
+
if leaked:
|
| 643 |
+
for pid in leaked:
|
| 644 |
+
try:
|
| 645 |
+
os.kill(pid, signal.SIGKILL)
|
| 646 |
+
except ProcessLookupError:
|
| 647 |
+
pass
|
| 648 |
+
raise CompilerSandboxError(f"compiler left detached processes: {leaked}")
|
| 649 |
+
if log.stat().st_size > MAX_LOG_BYTES:
|
| 650 |
+
raise CompilerSandboxError("compiler log exceeded 256 MiB")
|
| 651 |
+
|
| 652 |
+
shutil.rmtree(data)
|
| 653 |
+
validate_artifact_tree(build)
|
| 654 |
+
executable = build / EXECUTABLE_ENTRYPOINT
|
| 655 |
+
try:
|
| 656 |
+
metadata = executable.lstat()
|
| 657 |
+
except OSError as exc:
|
| 658 |
+
raise CompilerSandboxError(
|
| 659 |
+
"compile.sh did not produce root executable"
|
| 660 |
+
) from exc
|
| 661 |
+
if (
|
| 662 |
+
not stat.S_ISREG(metadata.st_mode)
|
| 663 |
+
or metadata.st_nlink != 1
|
| 664 |
+
or not stat.S_IMODE(metadata.st_mode) & 0o111
|
| 665 |
+
or executable.resolve() != executable
|
| 666 |
+
):
|
| 667 |
+
raise CompilerSandboxError(
|
| 668 |
+
"executable must be an independent regular executable at the build root"
|
| 669 |
+
)
|
| 670 |
+
digest = freeze_build_tree(build)
|
| 671 |
+
return CompiledArtifact(
|
| 672 |
+
source_root=source,
|
| 673 |
+
build_root=build,
|
| 674 |
+
executable=executable,
|
| 675 |
+
tree_sha256=digest,
|
| 676 |
+
build_log=log,
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
@dataclass
|
| 681 |
+
class ExecutableRuntime:
|
| 682 |
+
"""One foreground compiled candidate bound to one isolated DATA_DIR."""
|
| 683 |
+
|
| 684 |
+
build_root: Path
|
| 685 |
+
data_dir: Path
|
| 686 |
+
port: int
|
| 687 |
+
seed: int
|
| 688 |
+
timezone: str = "UTC"
|
| 689 |
+
log_path: Path | None = None
|
| 690 |
+
# RLIMIT_AS covers reserved virtual address space, not resident memory.
|
| 691 |
+
# Current Node/V8 runtimes reserve more than the 8192 MiB Harbor RSS
|
| 692 |
+
# budget before serving any request; keep the evaluator's cgroup budget
|
| 693 |
+
# authoritative while leaving enough address space for that reservation.
|
| 694 |
+
memory_mb: int = 16384
|
| 695 |
+
expected_tree_sha256: str | None = None
|
| 696 |
+
mailbox_environment: Mapping[str, str] | None = None
|
| 697 |
+
mailbox_connect_ports: frozenset[int] = frozenset()
|
| 698 |
+
evaluator_environment: Mapping[str, str] | None = None
|
| 699 |
+
worker_access_roots: tuple[Path, ...] = ()
|
| 700 |
+
process: subprocess.Popen[bytes] | None = None
|
| 701 |
+
_log_handle: Any | None = None
|
| 702 |
+
_cleanup_complete: bool = True
|
| 703 |
+
_control_write_fd: int | None = None
|
| 704 |
+
_broker_tid: int | None = None
|
| 705 |
+
_candidate_pid: int | None = None
|
| 706 |
+
|
| 707 |
+
def _environment(self) -> dict[str, str]:
|
| 708 |
+
data = self.data_dir.resolve()
|
| 709 |
+
environment = {
|
| 710 |
+
"PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
|
| 711 |
+
"LANG": "C.UTF-8",
|
| 712 |
+
"LC_ALL": "C.UTF-8",
|
| 713 |
+
"HOST": "127.0.0.1",
|
| 714 |
+
"PORT": str(self.port),
|
| 715 |
+
"DATA_DIR": str(data),
|
| 716 |
+
"SEED": str(self.seed),
|
| 717 |
+
"TZ": self.timezone,
|
| 718 |
+
"HOME": str(data / "home"),
|
| 719 |
+
"TMPDIR": str(data / "tmp"),
|
| 720 |
+
"XDG_CACHE_HOME": str(data / "xdg-cache"),
|
| 721 |
+
"XDG_CONFIG_HOME": str(data / "xdg-config"),
|
| 722 |
+
"XDG_DATA_HOME": str(data / "xdg-data"),
|
| 723 |
+
"WEBSITEBENCH_DEPLOYMENT_ABI": DEPLOYMENT_ABI,
|
| 724 |
+
}
|
| 725 |
+
if self.mailbox_environment is not None:
|
| 726 |
+
unknown = set(self.mailbox_environment) - CANDIDATE_MAIL_ENVIRONMENT
|
| 727 |
+
if unknown:
|
| 728 |
+
raise CompilerSandboxError(
|
| 729 |
+
f"candidate mailbox environment has unknown names: {sorted(unknown)}"
|
| 730 |
+
)
|
| 731 |
+
environment.update(
|
| 732 |
+
{name: str(value) for name, value in self.mailbox_environment.items()}
|
| 733 |
+
)
|
| 734 |
+
if self.evaluator_environment is not None:
|
| 735 |
+
unknown = set(self.evaluator_environment) - CANDIDATE_EVALUATOR_ENVIRONMENT
|
| 736 |
+
if unknown:
|
| 737 |
+
raise CompilerSandboxError(
|
| 738 |
+
"candidate evaluator environment has unknown names: "
|
| 739 |
+
f"{sorted(unknown)}"
|
| 740 |
+
)
|
| 741 |
+
if any(not str(value) for value in self.evaluator_environment.values()):
|
| 742 |
+
raise CompilerSandboxError(
|
| 743 |
+
"candidate evaluator environment values must be non-empty"
|
| 744 |
+
)
|
| 745 |
+
environment.update(
|
| 746 |
+
{name: str(value) for name, value in self.evaluator_environment.items()}
|
| 747 |
+
)
|
| 748 |
+
return environment
|
| 749 |
+
|
| 750 |
+
def _sandbox_command(
|
| 751 |
+
self,
|
| 752 |
+
*,
|
| 753 |
+
build: Path,
|
| 754 |
+
executable: Path,
|
| 755 |
+
control_read_fd: int,
|
| 756 |
+
broker_write_fd: int,
|
| 757 |
+
credentials: tuple[int, int] | None,
|
| 758 |
+
) -> list[str]:
|
| 759 |
+
sandbox_path = Path(sandbox.__file__).resolve(strict=True)
|
| 760 |
+
command = [
|
| 761 |
+
os.sys.executable,
|
| 762 |
+
str(sandbox_path),
|
| 763 |
+
"--root",
|
| 764 |
+
str(build),
|
| 765 |
+
"--data",
|
| 766 |
+
str(self.data_dir.resolve()),
|
| 767 |
+
"--bind-port",
|
| 768 |
+
str(self.port),
|
| 769 |
+
"--connect-port",
|
| 770 |
+
str(self.port),
|
| 771 |
+
]
|
| 772 |
+
for connect_port in sorted(self.mailbox_connect_ports):
|
| 773 |
+
command.extend(("--connect-port", str(connect_port)))
|
| 774 |
+
if credentials is not None:
|
| 775 |
+
uid, gid = credentials
|
| 776 |
+
command.extend(("--uid", str(uid), "--gid", str(gid)))
|
| 777 |
+
command.extend(
|
| 778 |
+
(
|
| 779 |
+
"--file-size-limit-bytes",
|
| 780 |
+
str(MAX_LOG_BYTES),
|
| 781 |
+
"--broker-tid-fd",
|
| 782 |
+
str(broker_write_fd),
|
| 783 |
+
"--control-fd",
|
| 784 |
+
str(control_read_fd),
|
| 785 |
+
"--",
|
| 786 |
+
str(executable),
|
| 787 |
+
)
|
| 788 |
+
)
|
| 789 |
+
return command
|
| 790 |
+
|
| 791 |
+
def _attest_worker_identity(
|
| 792 |
+
self,
|
| 793 |
+
*,
|
| 794 |
+
expected_uid: int,
|
| 795 |
+
expected_gid: int,
|
| 796 |
+
) -> None:
|
| 797 |
+
if self.process is None or self._broker_tid is None or self._candidate_pid is None:
|
| 798 |
+
raise OSError(errno.EIO, "sandbox identity proof is incomplete")
|
| 799 |
+
launcher_pid = self.process.pid
|
| 800 |
+
broker_status = Path(
|
| 801 |
+
f"/proc/{launcher_pid}/task/{self._broker_tid}/status"
|
| 802 |
+
)
|
| 803 |
+
candidate_status = Path(f"/proc/{self._candidate_pid}/status")
|
| 804 |
+
broker_uid, broker_gid, _broker_parent = _proc_status_identity(broker_status)
|
| 805 |
+
candidate_uid, candidate_gid, candidate_parent = _proc_status_identity(
|
| 806 |
+
candidate_status
|
| 807 |
+
)
|
| 808 |
+
expected_uids = (expected_uid,) * 4
|
| 809 |
+
expected_gids = (expected_gid,) * 4
|
| 810 |
+
if (
|
| 811 |
+
broker_uid != expected_uids
|
| 812 |
+
or broker_gid != expected_gids
|
| 813 |
+
or candidate_uid != expected_uids
|
| 814 |
+
or candidate_gid != expected_gids
|
| 815 |
+
or candidate_parent != launcher_pid
|
| 816 |
+
):
|
| 817 |
+
raise OSError(
|
| 818 |
+
errno.EPERM,
|
| 819 |
+
"sandbox broker or candidate retained an unexpected OS identity",
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
def _preexec(self) -> None:
|
| 823 |
+
os.umask(0o077)
|
| 824 |
+
if resource is not None:
|
| 825 |
+
memory = self.memory_mb * 1024 * 1024
|
| 826 |
+
resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
|
| 827 |
+
resource.setrlimit(resource.RLIMIT_NOFILE, (1024, 1024))
|
| 828 |
+
resource.setrlimit(resource.RLIMIT_FSIZE, (MAX_LOG_BYTES, MAX_LOG_BYTES))
|
| 829 |
+
|
| 830 |
+
def start(self) -> None:
|
| 831 |
+
if not self._cleanup_complete:
|
| 832 |
+
raise CompilerSandboxError(
|
| 833 |
+
"runtime cleanup is incomplete; restart forbidden"
|
| 834 |
+
)
|
| 835 |
+
if self.process is not None and self.process.poll() is None:
|
| 836 |
+
raise CompilerSandboxError("compiled runtime is already running")
|
| 837 |
+
for connect_port in self.mailbox_connect_ports:
|
| 838 |
+
if not 1 <= connect_port <= 65535 or connect_port == self.port:
|
| 839 |
+
raise CompilerSandboxError("candidate mailbox connect port is invalid")
|
| 840 |
+
build = self.build_root.resolve(strict=True)
|
| 841 |
+
current_digest = tree_digest(build)
|
| 842 |
+
if current_digest == "": # pragma: no cover - digest is never empty
|
| 843 |
+
raise CompilerSandboxError("compiled build hash is unavailable")
|
| 844 |
+
if (
|
| 845 |
+
self.expected_tree_sha256 is not None
|
| 846 |
+
and current_digest != self.expected_tree_sha256
|
| 847 |
+
):
|
| 848 |
+
raise CompilerSandboxError("compiled build tree changed after freezing")
|
| 849 |
+
executable = build / EXECUTABLE_ENTRYPOINT
|
| 850 |
+
metadata = executable.lstat()
|
| 851 |
+
if not stat.S_ISREG(metadata.st_mode) or not metadata.st_mode & 0o111:
|
| 852 |
+
raise CompilerSandboxError("compiled executable contract changed")
|
| 853 |
+
credentials = _runtime_worker_credentials()
|
| 854 |
+
try:
|
| 855 |
+
_prepare_runtime_directories(
|
| 856 |
+
build,
|
| 857 |
+
self.data_dir.resolve(),
|
| 858 |
+
credentials,
|
| 859 |
+
worker_access_roots=self.worker_access_roots,
|
| 860 |
+
)
|
| 861 |
+
except OSError as exc:
|
| 862 |
+
raise RuntimeInfrastructureError(
|
| 863 |
+
"compiled runtime worker directories could not be prepared"
|
| 864 |
+
) from exc
|
| 865 |
+
if self.log_path is not None:
|
| 866 |
+
log = self.log_path.resolve()
|
| 867 |
+
data = self.data_dir.resolve()
|
| 868 |
+
if data not in log.parents:
|
| 869 |
+
raise CompilerSandboxError("runtime log must be inside DATA_DIR")
|
| 870 |
+
log.parent.mkdir(parents=True, exist_ok=True)
|
| 871 |
+
self._log_handle = log.open("ab")
|
| 872 |
+
control_read_fd, control_write_fd = os.pipe()
|
| 873 |
+
broker_read_fd, broker_write_fd = os.pipe()
|
| 874 |
+
os.set_blocking(broker_read_fd, False)
|
| 875 |
+
command = self._sandbox_command(
|
| 876 |
+
build=build,
|
| 877 |
+
executable=executable,
|
| 878 |
+
control_read_fd=control_read_fd,
|
| 879 |
+
broker_write_fd=broker_write_fd,
|
| 880 |
+
credentials=credentials,
|
| 881 |
+
)
|
| 882 |
+
try:
|
| 883 |
+
self.process = subprocess.Popen(
|
| 884 |
+
command,
|
| 885 |
+
cwd=build,
|
| 886 |
+
env=self._environment(),
|
| 887 |
+
stdin=subprocess.DEVNULL,
|
| 888 |
+
stdout=self._log_handle or subprocess.DEVNULL,
|
| 889 |
+
stderr=self._log_handle or subprocess.DEVNULL,
|
| 890 |
+
start_new_session=True,
|
| 891 |
+
preexec_fn=self._preexec,
|
| 892 |
+
pass_fds=(control_read_fd, broker_write_fd),
|
| 893 |
+
)
|
| 894 |
+
except BaseException:
|
| 895 |
+
os.close(control_read_fd)
|
| 896 |
+
os.close(control_write_fd)
|
| 897 |
+
os.close(broker_read_fd)
|
| 898 |
+
os.close(broker_write_fd)
|
| 899 |
+
self._close_log()
|
| 900 |
+
raise
|
| 901 |
+
os.close(control_read_fd)
|
| 902 |
+
os.close(broker_write_fd)
|
| 903 |
+
self._control_write_fd = control_write_fd
|
| 904 |
+
self._cleanup_complete = False
|
| 905 |
+
proof = b""
|
| 906 |
+
# Process creation can be delayed materially when several Harbor
|
| 907 |
+
# verifier shards contend for I/O. Identity proof is an
|
| 908 |
+
# infrastructure handshake, not candidate readiness, so give the
|
| 909 |
+
# trusted launcher enough time to report its already-created workers.
|
| 910 |
+
deadline = time.monotonic() + 15.0
|
| 911 |
+
try:
|
| 912 |
+
while b"\n" not in proof and time.monotonic() < deadline:
|
| 913 |
+
try:
|
| 914 |
+
proof += os.read(broker_read_fd, 128)
|
| 915 |
+
except BlockingIOError:
|
| 916 |
+
pass
|
| 917 |
+
if self.process.poll() is not None:
|
| 918 |
+
break
|
| 919 |
+
time.sleep(0.01)
|
| 920 |
+
except OSError as exc:
|
| 921 |
+
self.stop(timeout=1.0)
|
| 922 |
+
raise RuntimeInfrastructureError(
|
| 923 |
+
"compiled runtime sandbox identity proof could not be read"
|
| 924 |
+
) from exc
|
| 925 |
+
finally:
|
| 926 |
+
os.close(broker_read_fd)
|
| 927 |
+
try:
|
| 928 |
+
proof_fields = proof.splitlines()[0].split()
|
| 929 |
+
if len(proof_fields) != 2:
|
| 930 |
+
raise ValueError("sandbox proof must contain two process IDs")
|
| 931 |
+
self._broker_tid, self._candidate_pid = map(int, proof_fields)
|
| 932 |
+
except (ValueError, IndexError):
|
| 933 |
+
self._broker_tid = None
|
| 934 |
+
self._candidate_pid = None
|
| 935 |
+
if (
|
| 936 |
+
self._broker_tid is not None
|
| 937 |
+
and not Path(f"/proc/{self.process.pid}/task/{self._broker_tid}").is_dir()
|
| 938 |
+
):
|
| 939 |
+
self._broker_tid = None
|
| 940 |
+
if self._broker_tid is None or self._candidate_pid is None:
|
| 941 |
+
self.stop(timeout=1.0)
|
| 942 |
+
raise RuntimeInfrastructureError(
|
| 943 |
+
"compiled runtime sandbox did not attest its broker and candidate IDs"
|
| 944 |
+
)
|
| 945 |
+
expected_uid, expected_gid = credentials or (os.geteuid(), os.getegid())
|
| 946 |
+
try:
|
| 947 |
+
self._attest_worker_identity(
|
| 948 |
+
expected_uid=expected_uid,
|
| 949 |
+
expected_gid=expected_gid,
|
| 950 |
+
)
|
| 951 |
+
except OSError as exc:
|
| 952 |
+
self.stop(timeout=1.0)
|
| 953 |
+
raise RuntimeInfrastructureError(
|
| 954 |
+
"compiled runtime sandbox worker identity could not be verified"
|
| 955 |
+
) from exc
|
| 956 |
+
|
| 957 |
+
def ready(self, *, timeout: float = 30.0) -> bool:
|
| 958 |
+
deadline = time.monotonic() + timeout
|
| 959 |
+
urls = [f"http://127.0.0.1:{self.port}{path}" for path in HEALTH_PATHS]
|
| 960 |
+
while time.monotonic() < deadline:
|
| 961 |
+
if self.process is None or self.process.poll() is not None:
|
| 962 |
+
return False
|
| 963 |
+
for url in urls:
|
| 964 |
+
try:
|
| 965 |
+
request = urllib.request.Request(url, method="GET")
|
| 966 |
+
with urllib.request.urlopen(request, timeout=0.5) as response:
|
| 967 |
+
payload = response.read(4096)
|
| 968 |
+
if (
|
| 969 |
+
response.status == 200
|
| 970 |
+
and json.loads(payload) == HEALTH_BODY
|
| 971 |
+
):
|
| 972 |
+
return self.process.poll() is None
|
| 973 |
+
except (
|
| 974 |
+
OSError,
|
| 975 |
+
ValueError,
|
| 976 |
+
urllib.error.URLError,
|
| 977 |
+
json.JSONDecodeError,
|
| 978 |
+
):
|
| 979 |
+
pass
|
| 980 |
+
time.sleep(0.05)
|
| 981 |
+
return False
|
| 982 |
+
|
| 983 |
+
def stop(
|
| 984 |
+
self, *, timeout: float = 10.0, accept_forced: bool = False
|
| 985 |
+
) -> bool:
|
| 986 |
+
if self.process is None:
|
| 987 |
+
self._close_control()
|
| 988 |
+
self._close_log()
|
| 989 |
+
self._cleanup_complete = True
|
| 990 |
+
return True
|
| 991 |
+
if self._control_write_fd is None:
|
| 992 |
+
graceful = _terminate_group(
|
| 993 |
+
self.process, timeout, accept_forced=accept_forced
|
| 994 |
+
)
|
| 995 |
+
else:
|
| 996 |
+
graceful = _stop_controlled_group(
|
| 997 |
+
self.process,
|
| 998 |
+
self._control_write_fd,
|
| 999 |
+
timeout,
|
| 1000 |
+
accept_forced=accept_forced,
|
| 1001 |
+
)
|
| 1002 |
+
self._close_control()
|
| 1003 |
+
self._close_log()
|
| 1004 |
+
self._cleanup_complete = graceful
|
| 1005 |
+
self._broker_tid = None
|
| 1006 |
+
self._candidate_pid = None
|
| 1007 |
+
return graceful
|
| 1008 |
+
|
| 1009 |
+
def _close_control(self) -> None:
|
| 1010 |
+
if self._control_write_fd is not None:
|
| 1011 |
+
try:
|
| 1012 |
+
os.close(self._control_write_fd)
|
| 1013 |
+
except OSError:
|
| 1014 |
+
pass
|
| 1015 |
+
self._control_write_fd = None
|
| 1016 |
+
|
| 1017 |
+
def _close_log(self) -> None:
|
| 1018 |
+
if self._log_handle is not None:
|
| 1019 |
+
self._log_handle.flush()
|
| 1020 |
+
os.fsync(self._log_handle.fileno())
|
| 1021 |
+
self._log_handle.close()
|
| 1022 |
+
self._log_handle = None
|
| 1023 |
+
|
| 1024 |
+
|
| 1025 |
+
def validate_runtime_lifecycle(
|
| 1026 |
+
artifact: CompiledArtifact,
|
| 1027 |
+
*,
|
| 1028 |
+
port: int,
|
| 1029 |
+
seed: int,
|
| 1030 |
+
working_root: Path | str,
|
| 1031 |
+
worker_access_roots: Sequence[Path | str],
|
| 1032 |
+
timezone: str = "UTC",
|
| 1033 |
+
) -> dict[str, Any]:
|
| 1034 |
+
"""Probe health, foreground/SIGTERM, restart persistence and new-dir isolation."""
|
| 1035 |
+
|
| 1036 |
+
root = Path(working_root).resolve()
|
| 1037 |
+
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
| 1038 |
+
first_data = root / "data-first"
|
| 1039 |
+
second_data = root / "data-second"
|
| 1040 |
+
first_data.mkdir(mode=0o700)
|
| 1041 |
+
second_data.mkdir(mode=0o700)
|
| 1042 |
+
sentinel = first_data / ".websitebench-persistence"
|
| 1043 |
+
sentinel.write_text(f"{seed}\n", encoding="ascii")
|
| 1044 |
+
first = ExecutableRuntime(
|
| 1045 |
+
artifact.build_root,
|
| 1046 |
+
first_data,
|
| 1047 |
+
port,
|
| 1048 |
+
seed,
|
| 1049 |
+
timezone,
|
| 1050 |
+
first_data / "runtime.log",
|
| 1051 |
+
expected_tree_sha256=artifact.tree_sha256,
|
| 1052 |
+
worker_access_roots=tuple(Path(value) for value in worker_access_roots),
|
| 1053 |
+
)
|
| 1054 |
+
first.start()
|
| 1055 |
+
healthy = first.ready()
|
| 1056 |
+
graceful = first.stop(timeout=10.0)
|
| 1057 |
+
sentinel_persisted = sentinel.read_text(encoding="ascii") == f"{seed}\n"
|
| 1058 |
+
restarted = False
|
| 1059 |
+
if graceful:
|
| 1060 |
+
first.start()
|
| 1061 |
+
restarted = first.ready()
|
| 1062 |
+
graceful = first.stop(timeout=10.0) and graceful
|
| 1063 |
+
second = ExecutableRuntime(
|
| 1064 |
+
artifact.build_root,
|
| 1065 |
+
second_data,
|
| 1066 |
+
port,
|
| 1067 |
+
seed,
|
| 1068 |
+
timezone,
|
| 1069 |
+
second_data / "runtime.log",
|
| 1070 |
+
expected_tree_sha256=artifact.tree_sha256,
|
| 1071 |
+
worker_access_roots=tuple(Path(value) for value in worker_access_roots),
|
| 1072 |
+
)
|
| 1073 |
+
second.start()
|
| 1074 |
+
second_healthy = second.ready()
|
| 1075 |
+
second_graceful = second.stop(timeout=10.0)
|
| 1076 |
+
isolated = (
|
| 1077 |
+
second_healthy
|
| 1078 |
+
and second_graceful
|
| 1079 |
+
and not (second_data / sentinel.name).exists()
|
| 1080 |
+
)
|
| 1081 |
+
return {
|
| 1082 |
+
"deployment_abi": DEPLOYMENT_ABI,
|
| 1083 |
+
"health": healthy,
|
| 1084 |
+
"foreground": healthy,
|
| 1085 |
+
"sigterm": graceful,
|
| 1086 |
+
"restart": restarted,
|
| 1087 |
+
"persistence": sentinel_persisted,
|
| 1088 |
+
"new_data_dir_health": second_healthy,
|
| 1089 |
+
"new_data_dir_isolation": isolated,
|
| 1090 |
+
"tree_sha256": artifact.tree_sha256,
|
| 1091 |
+
"valid": all(
|
| 1092 |
+
(
|
| 1093 |
+
healthy,
|
| 1094 |
+
graceful,
|
| 1095 |
+
restarted,
|
| 1096 |
+
sentinel_persisted,
|
| 1097 |
+
second_healthy,
|
| 1098 |
+
second_graceful,
|
| 1099 |
+
isolated,
|
| 1100 |
+
)
|
| 1101 |
+
),
|
| 1102 |
+
}
|
| 1103 |
+
|
| 1104 |
+
|
| 1105 |
+
__all__ = [
|
| 1106 |
+
"COMPILE_ENTRYPOINT",
|
| 1107 |
+
"DEFAULT_COMPILE_TIMEOUT",
|
| 1108 |
+
"DEPLOYMENT_ABI",
|
| 1109 |
+
"EXECUTABLE_ENTRYPOINT",
|
| 1110 |
+
"HEALTH_BODY",
|
| 1111 |
+
"HEALTH_PATH",
|
| 1112 |
+
"HEALTH_PATHS",
|
| 1113 |
+
"LEGACY_HEALTH_PATHS",
|
| 1114 |
+
"MAX_LOG_BYTES",
|
| 1115 |
+
"RUNTIME_PROCESS_MODEL",
|
| 1116 |
+
"RuntimeInfrastructureError",
|
| 1117 |
+
"WORKER_OS_GID",
|
| 1118 |
+
"WORKER_OS_UID",
|
| 1119 |
+
"CompiledArtifact",
|
| 1120 |
+
"CompilerSandboxError",
|
| 1121 |
+
"ExecutableRuntime",
|
| 1122 |
+
"compile_candidate",
|
| 1123 |
+
"freeze_build_tree",
|
| 1124 |
+
"quarantine_artifact",
|
| 1125 |
+
"tree_digest",
|
| 1126 |
+
"validate_artifact_tree",
|
| 1127 |
+
"validate_runtime_lifecycle",
|
| 1128 |
+
]
|
tasks/columbia/environment/candidate-abi/websitebench/harbor/sandbox.py
ADDED
|
@@ -0,0 +1,841 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Linux kernel sandbox launcher for untrusted Harbor candidates.
|
| 2 |
+
|
| 3 |
+
The launcher is executed by the privileged verifier, installs an irreversible
|
| 4 |
+
Landlock/seccomp policy, drops to the opaque worker UID, and only then execs the
|
| 5 |
+
candidate entrypoint. It deliberately has no dependency outside the standard
|
| 6 |
+
library so the formal verifier image has a small, inspectable trusted surface.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import array
|
| 13 |
+
import ctypes
|
| 14 |
+
import errno
|
| 15 |
+
import fcntl
|
| 16 |
+
import os
|
| 17 |
+
import platform
|
| 18 |
+
import resource
|
| 19 |
+
import signal
|
| 20 |
+
import socket
|
| 21 |
+
import stat
|
| 22 |
+
import struct
|
| 23 |
+
import threading
|
| 24 |
+
import time
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Sequence
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
PR_SET_NO_NEW_PRIVS = 38
|
| 30 |
+
PR_SET_DUMPABLE = 4
|
| 31 |
+
PR_SET_SECCOMP = 22
|
| 32 |
+
SECCOMP_MODE_FILTER = 2
|
| 33 |
+
SECCOMP_RET_KILL_PROCESS = 0x80000000
|
| 34 |
+
SECCOMP_RET_ERRNO = 0x00050000
|
| 35 |
+
SECCOMP_RET_USER_NOTIF = 0x7FC00000
|
| 36 |
+
SECCOMP_RET_ALLOW = 0x7FFF0000
|
| 37 |
+
SECCOMP_FILTER_FLAG_NEW_LISTENER = 1 << 3
|
| 38 |
+
SECCOMP_SET_MODE_FILTER = 1
|
| 39 |
+
SECCOMP_GET_ACTION_AVAIL = 2
|
| 40 |
+
|
| 41 |
+
BPF_LD_W_ABS = 0x20
|
| 42 |
+
BPF_JMP_JEQ_K = 0x15
|
| 43 |
+
BPF_JMP_JSET_K = 0x45
|
| 44 |
+
BPF_ALU_AND_K = 0x54
|
| 45 |
+
BPF_RET_K = 0x06
|
| 46 |
+
|
| 47 |
+
LANDLOCK_CREATE_RULESET_VERSION = 1
|
| 48 |
+
LANDLOCK_RULE_PATH_BENEATH = 1
|
| 49 |
+
LANDLOCK_RULE_NET_PORT = 2
|
| 50 |
+
LANDLOCK_ACCESS_FS_EXECUTE = 1 << 0
|
| 51 |
+
LANDLOCK_ACCESS_FS_WRITE_FILE = 1 << 1
|
| 52 |
+
LANDLOCK_ACCESS_FS_READ_FILE = 1 << 2
|
| 53 |
+
LANDLOCK_ACCESS_FS_READ_DIR = 1 << 3
|
| 54 |
+
LANDLOCK_ACCESS_FS_REMOVE_DIR = 1 << 4
|
| 55 |
+
LANDLOCK_ACCESS_FS_REMOVE_FILE = 1 << 5
|
| 56 |
+
LANDLOCK_ACCESS_FS_MAKE_CHAR = 1 << 6
|
| 57 |
+
LANDLOCK_ACCESS_FS_MAKE_DIR = 1 << 7
|
| 58 |
+
LANDLOCK_ACCESS_FS_MAKE_REG = 1 << 8
|
| 59 |
+
LANDLOCK_ACCESS_FS_MAKE_SOCK = 1 << 9
|
| 60 |
+
LANDLOCK_ACCESS_FS_MAKE_FIFO = 1 << 10
|
| 61 |
+
LANDLOCK_ACCESS_FS_MAKE_BLOCK = 1 << 11
|
| 62 |
+
LANDLOCK_ACCESS_FS_MAKE_SYM = 1 << 12
|
| 63 |
+
LANDLOCK_ACCESS_FS_REFER = 1 << 13
|
| 64 |
+
LANDLOCK_ACCESS_FS_TRUNCATE = 1 << 14
|
| 65 |
+
LANDLOCK_ACCESS_FS_IOCTL_DEV = 1 << 15
|
| 66 |
+
LANDLOCK_ACCESS_NET_BIND_TCP = 1 << 0
|
| 67 |
+
LANDLOCK_ACCESS_NET_CONNECT_TCP = 1 << 1
|
| 68 |
+
|
| 69 |
+
_FS_ABI_1 = (1 << 13) - 1
|
| 70 |
+
_FS_ABI_2 = _FS_ABI_1 | LANDLOCK_ACCESS_FS_REFER
|
| 71 |
+
_FS_ABI_3 = _FS_ABI_2 | LANDLOCK_ACCESS_FS_TRUNCATE
|
| 72 |
+
_FS_ABI_5 = _FS_ABI_3 | LANDLOCK_ACCESS_FS_IOCTL_DEV
|
| 73 |
+
_FS_READ_EXECUTE = (
|
| 74 |
+
LANDLOCK_ACCESS_FS_EXECUTE
|
| 75 |
+
| LANDLOCK_ACCESS_FS_READ_FILE
|
| 76 |
+
| LANDLOCK_ACCESS_FS_READ_DIR
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class _RulesetAttr(ctypes.Structure):
|
| 81 |
+
_fields_ = [
|
| 82 |
+
("handled_access_fs", ctypes.c_uint64),
|
| 83 |
+
("handled_access_net", ctypes.c_uint64),
|
| 84 |
+
]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class _PathBeneathAttr(ctypes.Structure):
|
| 88 |
+
_fields_ = [
|
| 89 |
+
("allowed_access", ctypes.c_uint64),
|
| 90 |
+
("parent_fd", ctypes.c_int32),
|
| 91 |
+
("reserved", ctypes.c_uint32),
|
| 92 |
+
]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class _NetPortAttr(ctypes.Structure):
|
| 96 |
+
_fields_ = [("allowed_access", ctypes.c_uint64), ("port", ctypes.c_uint64)]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class _SockFilter(ctypes.Structure):
|
| 100 |
+
_fields_ = [
|
| 101 |
+
("code", ctypes.c_ushort),
|
| 102 |
+
("jt", ctypes.c_ubyte),
|
| 103 |
+
("jf", ctypes.c_ubyte),
|
| 104 |
+
("k", ctypes.c_uint32),
|
| 105 |
+
]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class _SockFprog(ctypes.Structure):
|
| 109 |
+
_fields_ = [("len", ctypes.c_ushort), ("filter", ctypes.POINTER(_SockFilter))]
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
_SECCOMP_NOTIF_FORMAT = "=QIIiIQQQQQQQ"
|
| 113 |
+
_SECCOMP_RESP_FORMAT = "=QqiI"
|
| 114 |
+
_SECCOMP_NOTIF_SIZE = struct.calcsize(_SECCOMP_NOTIF_FORMAT)
|
| 115 |
+
_SECCOMP_RESP_SIZE = struct.calcsize(_SECCOMP_RESP_FORMAT)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _iowr(kind: int, number: int, size: int) -> int:
|
| 119 |
+
return (3 << 30) | (size << 16) | (kind << 8) | number
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
_SECCOMP_IOCTL_NOTIF_RECV = _iowr(ord("!"), 0, _SECCOMP_NOTIF_SIZE)
|
| 123 |
+
_SECCOMP_IOCTL_NOTIF_SEND = _iowr(ord("!"), 1, _SECCOMP_RESP_SIZE)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _architecture() -> tuple[int, int, int, int, tuple[int, ...]]:
|
| 127 |
+
machine = platform.machine().lower()
|
| 128 |
+
if machine in {"x86_64", "amd64"}:
|
| 129 |
+
# AUDIT_ARCH_X86_64, socket(2), and shared cross-process facilities.
|
| 130 |
+
return (
|
| 131 |
+
0xC000003E,
|
| 132 |
+
41,
|
| 133 |
+
72,
|
| 134 |
+
317,
|
| 135 |
+
(
|
| 136 |
+
29,
|
| 137 |
+
30,
|
| 138 |
+
31,
|
| 139 |
+
57,
|
| 140 |
+
58,
|
| 141 |
+
64,
|
| 142 |
+
65,
|
| 143 |
+
66,
|
| 144 |
+
67,
|
| 145 |
+
68,
|
| 146 |
+
69,
|
| 147 |
+
70,
|
| 148 |
+
71,
|
| 149 |
+
109,
|
| 150 |
+
112,
|
| 151 |
+
240,
|
| 152 |
+
241,
|
| 153 |
+
242,
|
| 154 |
+
243,
|
| 155 |
+
244,
|
| 156 |
+
245,
|
| 157 |
+
248,
|
| 158 |
+
249,
|
| 159 |
+
250,
|
| 160 |
+
253,
|
| 161 |
+
254,
|
| 162 |
+
255,
|
| 163 |
+
294,
|
| 164 |
+
298,
|
| 165 |
+
300,
|
| 166 |
+
301,
|
| 167 |
+
425,
|
| 168 |
+
73,
|
| 169 |
+
),
|
| 170 |
+
)
|
| 171 |
+
if machine in {"aarch64", "arm64"}:
|
| 172 |
+
return (
|
| 173 |
+
0xC00000B7,
|
| 174 |
+
198,
|
| 175 |
+
25,
|
| 176 |
+
277,
|
| 177 |
+
tuple(range(180, 198))
|
| 178 |
+
+ (26, 27, 28, 32, 154, 157, 217, 218, 219, 241, 262, 263, 425),
|
| 179 |
+
)
|
| 180 |
+
raise OSError(errno.ENOTSUP, f"unsupported verifier architecture: {machine}")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _syscalls() -> tuple[int, int, int]:
|
| 184 |
+
machine = platform.machine().lower()
|
| 185 |
+
if machine in {"x86_64", "amd64", "aarch64", "arm64"}:
|
| 186 |
+
return 444, 445, 446
|
| 187 |
+
raise OSError(errno.ENOTSUP, f"unsupported verifier architecture: {machine}")
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def sandbox_runtime_fingerprint() -> dict[str, object]:
|
| 191 |
+
"""Return trusted kernel capabilities required by the candidate sandbox."""
|
| 192 |
+
|
| 193 |
+
audit_arch, socket_syscall, _fcntl_syscall, seccomp_syscall, _denied = (
|
| 194 |
+
_architecture()
|
| 195 |
+
)
|
| 196 |
+
create_ruleset, _add_rule, _restrict_self = _syscalls()
|
| 197 |
+
libc = ctypes.CDLL(None, use_errno=True)
|
| 198 |
+
abi = int(libc.syscall(create_ruleset, 0, 0, LANDLOCK_CREATE_RULESET_VERSION))
|
| 199 |
+
action = ctypes.c_uint32(SECCOMP_RET_USER_NOTIF)
|
| 200 |
+
user_notification = (
|
| 201 |
+
libc.syscall(
|
| 202 |
+
seccomp_syscall,
|
| 203 |
+
SECCOMP_GET_ACTION_AVAIL,
|
| 204 |
+
0,
|
| 205 |
+
ctypes.byref(action),
|
| 206 |
+
)
|
| 207 |
+
== 0
|
| 208 |
+
)
|
| 209 |
+
x32_unavailable = True
|
| 210 |
+
if audit_arch == 0xC000003E:
|
| 211 |
+
ctypes.set_errno(0)
|
| 212 |
+
result = libc.syscall(0x40000000 | socket_syscall, -1, -1, -1)
|
| 213 |
+
x32_unavailable = result == -1 and ctypes.get_errno() == errno.ENOSYS
|
| 214 |
+
return {
|
| 215 |
+
"schema": "websitebench.harbor.sandbox-runtime",
|
| 216 |
+
"architecture": platform.machine().lower(),
|
| 217 |
+
"landlock_abi": abi,
|
| 218 |
+
"seccomp_user_notification": user_notification,
|
| 219 |
+
"x32_unavailable": x32_unavailable,
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def sandbox_preflight() -> dict[str, object]:
|
| 224 |
+
"""Fail closed before scoring when the verifier kernel cannot sandbox."""
|
| 225 |
+
|
| 226 |
+
fingerprint = sandbox_runtime_fingerprint()
|
| 227 |
+
if (
|
| 228 |
+
int(fingerprint["landlock_abi"]) < 4
|
| 229 |
+
or fingerprint["seccomp_user_notification"] is not True
|
| 230 |
+
or fingerprint["x32_unavailable"] is not True
|
| 231 |
+
):
|
| 232 |
+
raise OSError(errno.ENOTSUP, f"candidate sandbox unavailable: {fingerprint}")
|
| 233 |
+
child = os.fork()
|
| 234 |
+
if child == 0:
|
| 235 |
+
try:
|
| 236 |
+
_landlock(Path("/"), Path("/tmp"), 65534, {65534})
|
| 237 |
+
listener = _seccomp()
|
| 238 |
+
os.close(listener)
|
| 239 |
+
os._exit(0)
|
| 240 |
+
except BaseException:
|
| 241 |
+
os._exit(1)
|
| 242 |
+
_waited, status = os.waitpid(child, 0)
|
| 243 |
+
if not os.WIFEXITED(status) or os.WEXITSTATUS(status) != 0:
|
| 244 |
+
raise OSError(errno.ENOTSUP, "candidate sandbox enforcement probe failed")
|
| 245 |
+
fingerprint["enforcement_probe_passed"] = True
|
| 246 |
+
return fingerprint
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _landlock(
|
| 250 |
+
root: Path,
|
| 251 |
+
data: Path,
|
| 252 |
+
bind_port: int,
|
| 253 |
+
connect_ports: set[int],
|
| 254 |
+
read_paths: Sequence[Path] = (),
|
| 255 |
+
) -> None:
|
| 256 |
+
libc = ctypes.CDLL(None, use_errno=True)
|
| 257 |
+
create_ruleset, add_rule, restrict_self = _syscalls()
|
| 258 |
+
abi = int(libc.syscall(create_ruleset, 0, 0, LANDLOCK_CREATE_RULESET_VERSION))
|
| 259 |
+
if abi < 4:
|
| 260 |
+
code = ctypes.get_errno() if abi < 0 else errno.ENOTSUP
|
| 261 |
+
raise OSError(code, "Landlock ABI 4 or newer is required")
|
| 262 |
+
|
| 263 |
+
handled_fs = _FS_ABI_1
|
| 264 |
+
if abi >= 2:
|
| 265 |
+
handled_fs = _FS_ABI_2
|
| 266 |
+
if abi >= 3:
|
| 267 |
+
handled_fs = _FS_ABI_3
|
| 268 |
+
if abi >= 5:
|
| 269 |
+
handled_fs = _FS_ABI_5
|
| 270 |
+
handled_net = LANDLOCK_ACCESS_NET_BIND_TCP | LANDLOCK_ACCESS_NET_CONNECT_TCP
|
| 271 |
+
attributes = _RulesetAttr(handled_fs, handled_net)
|
| 272 |
+
ruleset_fd = int(
|
| 273 |
+
libc.syscall(
|
| 274 |
+
create_ruleset,
|
| 275 |
+
ctypes.byref(attributes),
|
| 276 |
+
ctypes.sizeof(attributes),
|
| 277 |
+
0,
|
| 278 |
+
)
|
| 279 |
+
)
|
| 280 |
+
if ruleset_fd < 0:
|
| 281 |
+
raise OSError(ctypes.get_errno(), "cannot create Landlock ruleset")
|
| 282 |
+
|
| 283 |
+
def add_path(path: Path, access: int) -> None:
|
| 284 |
+
if not path.exists():
|
| 285 |
+
return
|
| 286 |
+
descriptor = os.open(path, os.O_PATH | os.O_CLOEXEC)
|
| 287 |
+
try:
|
| 288 |
+
rule = _PathBeneathAttr(access & handled_fs, descriptor, 0)
|
| 289 |
+
if (
|
| 290 |
+
libc.syscall(
|
| 291 |
+
add_rule,
|
| 292 |
+
ruleset_fd,
|
| 293 |
+
LANDLOCK_RULE_PATH_BENEATH,
|
| 294 |
+
ctypes.byref(rule),
|
| 295 |
+
0,
|
| 296 |
+
)
|
| 297 |
+
!= 0
|
| 298 |
+
):
|
| 299 |
+
raise OSError(ctypes.get_errno(), f"cannot allow sandbox path: {path}")
|
| 300 |
+
finally:
|
| 301 |
+
os.close(descriptor)
|
| 302 |
+
|
| 303 |
+
try:
|
| 304 |
+
for path in (
|
| 305 |
+
root,
|
| 306 |
+
Path("/usr"),
|
| 307 |
+
Path("/bin"),
|
| 308 |
+
Path("/lib"),
|
| 309 |
+
Path("/lib64"),
|
| 310 |
+
Path("/etc"),
|
| 311 |
+
*read_paths,
|
| 312 |
+
):
|
| 313 |
+
add_path(path, _FS_READ_EXECUTE)
|
| 314 |
+
for path in (
|
| 315 |
+
Path("/dev/null"),
|
| 316 |
+
Path("/dev/zero"),
|
| 317 |
+
Path("/dev/random"),
|
| 318 |
+
Path("/dev/urandom"),
|
| 319 |
+
Path("/dev/full"),
|
| 320 |
+
Path("/dev/tty"),
|
| 321 |
+
):
|
| 322 |
+
add_path(path, LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_WRITE_FILE)
|
| 323 |
+
add_path(data, handled_fs)
|
| 324 |
+
|
| 325 |
+
for access, port in (
|
| 326 |
+
(LANDLOCK_ACCESS_NET_BIND_TCP, bind_port),
|
| 327 |
+
*(
|
| 328 |
+
(LANDLOCK_ACCESS_NET_CONNECT_TCP, port)
|
| 329 |
+
for port in sorted(connect_ports)
|
| 330 |
+
),
|
| 331 |
+
):
|
| 332 |
+
rule = _NetPortAttr(access, port)
|
| 333 |
+
if (
|
| 334 |
+
libc.syscall(
|
| 335 |
+
add_rule,
|
| 336 |
+
ruleset_fd,
|
| 337 |
+
LANDLOCK_RULE_NET_PORT,
|
| 338 |
+
ctypes.byref(rule),
|
| 339 |
+
0,
|
| 340 |
+
)
|
| 341 |
+
!= 0
|
| 342 |
+
):
|
| 343 |
+
raise OSError(ctypes.get_errno(), "cannot add Landlock TCP rule")
|
| 344 |
+
|
| 345 |
+
if libc.prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
|
| 346 |
+
raise OSError(ctypes.get_errno(), "cannot set no_new_privs")
|
| 347 |
+
if libc.syscall(restrict_self, ruleset_fd, 0) != 0:
|
| 348 |
+
raise OSError(ctypes.get_errno(), "cannot enforce Landlock ruleset")
|
| 349 |
+
finally:
|
| 350 |
+
os.close(ruleset_fd)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def _seccomp() -> int:
|
| 354 |
+
"""Install the filter and return its user-notification listener."""
|
| 355 |
+
|
| 356 |
+
audit_arch, socket_syscall, fcntl_syscall, seccomp_syscall, denied = _architecture()
|
| 357 |
+
instructions: list[tuple[int, int, int, int]] = [
|
| 358 |
+
(BPF_LD_W_ABS, 0, 0, 4),
|
| 359 |
+
(BPF_JMP_JEQ_K, 1, 0, audit_arch),
|
| 360 |
+
(BPF_RET_K, 0, 0, SECCOMP_RET_KILL_PROCESS),
|
| 361 |
+
(BPF_LD_W_ABS, 0, 0, 0),
|
| 362 |
+
]
|
| 363 |
+
if audit_arch == 0xC000003E:
|
| 364 |
+
instructions.extend(
|
| 365 |
+
[
|
| 366 |
+
(BPF_JMP_JSET_K, 0, 1, 0x40000000),
|
| 367 |
+
(BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
|
| 368 |
+
]
|
| 369 |
+
)
|
| 370 |
+
# Force clone3 callers onto the inspectable clone/fork fallback, then deny
|
| 371 |
+
# only process-style clone(SIGCHLD). Thread creation has a zero exit-signal
|
| 372 |
+
# byte and remains available to ASGI runtimes.
|
| 373 |
+
clone_syscall = 56 if audit_arch == 0xC000003E else 220
|
| 374 |
+
instructions.extend(
|
| 375 |
+
[
|
| 376 |
+
(BPF_JMP_JEQ_K, 0, 1, 435),
|
| 377 |
+
(BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.ENOSYS),
|
| 378 |
+
(BPF_LD_W_ABS, 0, 0, 0),
|
| 379 |
+
(BPF_JMP_JEQ_K, 0, 4, clone_syscall),
|
| 380 |
+
(BPF_LD_W_ABS, 0, 0, 16),
|
| 381 |
+
(BPF_ALU_AND_K, 0, 0, 0xFF),
|
| 382 |
+
(BPF_JMP_JEQ_K, 0, 1, signal.SIGCHLD),
|
| 383 |
+
(BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
|
| 384 |
+
(BPF_LD_W_ABS, 0, 0, 0),
|
| 385 |
+
]
|
| 386 |
+
)
|
| 387 |
+
for number in denied:
|
| 388 |
+
instructions.extend(
|
| 389 |
+
[
|
| 390 |
+
(BPF_JMP_JEQ_K, 0, 1, number),
|
| 391 |
+
(BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
|
| 392 |
+
]
|
| 393 |
+
)
|
| 394 |
+
# Classic and OFD byte-range locks are executed by the trusted broker.
|
| 395 |
+
# The tracee is never continued after a pathname/fd check: another tracee
|
| 396 |
+
# thread could otherwise replace the descriptor between check and use.
|
| 397 |
+
brokered_fcntl_commands = (5, 6, 7, 36, 37, 38)
|
| 398 |
+
instructions.extend(
|
| 399 |
+
[
|
| 400 |
+
(
|
| 401 |
+
BPF_JMP_JEQ_K,
|
| 402 |
+
0,
|
| 403 |
+
2 * len(brokered_fcntl_commands) + 2,
|
| 404 |
+
fcntl_syscall,
|
| 405 |
+
),
|
| 406 |
+
(BPF_LD_W_ABS, 0, 0, 24),
|
| 407 |
+
]
|
| 408 |
+
)
|
| 409 |
+
for command in brokered_fcntl_commands:
|
| 410 |
+
instructions.extend(
|
| 411 |
+
[
|
| 412 |
+
(BPF_JMP_JEQ_K, 0, 1, command),
|
| 413 |
+
(BPF_RET_K, 0, 0, SECCOMP_RET_USER_NOTIF),
|
| 414 |
+
]
|
| 415 |
+
)
|
| 416 |
+
instructions.append((BPF_LD_W_ABS, 0, 0, 0))
|
| 417 |
+
# socket(domain, type, protocol): permit only IPv4/IPv6 SOCK_STREAM.
|
| 418 |
+
instructions.extend(
|
| 419 |
+
[
|
| 420 |
+
(BPF_JMP_JEQ_K, 0, 8, socket_syscall),
|
| 421 |
+
(BPF_LD_W_ABS, 0, 0, 16),
|
| 422 |
+
(BPF_JMP_JEQ_K, 2, 0, 2),
|
| 423 |
+
(BPF_JMP_JEQ_K, 1, 0, 10),
|
| 424 |
+
(BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
|
| 425 |
+
(BPF_LD_W_ABS, 0, 0, 24),
|
| 426 |
+
(BPF_ALU_AND_K, 0, 0, 0xF),
|
| 427 |
+
(BPF_JMP_JEQ_K, 1, 0, 1),
|
| 428 |
+
(BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
|
| 429 |
+
(BPF_RET_K, 0, 0, SECCOMP_RET_ALLOW),
|
| 430 |
+
]
|
| 431 |
+
)
|
| 432 |
+
filters = (_SockFilter * len(instructions))(
|
| 433 |
+
*(_SockFilter(*instruction) for instruction in instructions)
|
| 434 |
+
)
|
| 435 |
+
program = _SockFprog(len(instructions), filters)
|
| 436 |
+
libc = ctypes.CDLL(None, use_errno=True)
|
| 437 |
+
listener = int(
|
| 438 |
+
libc.syscall(
|
| 439 |
+
seccomp_syscall,
|
| 440 |
+
SECCOMP_SET_MODE_FILTER,
|
| 441 |
+
SECCOMP_FILTER_FLAG_NEW_LISTENER,
|
| 442 |
+
ctypes.byref(program),
|
| 443 |
+
)
|
| 444 |
+
)
|
| 445 |
+
if listener < 0:
|
| 446 |
+
raise OSError(ctypes.get_errno(), "cannot install candidate seccomp filter")
|
| 447 |
+
return listener
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def _send_fd(channel: socket.socket, descriptor: int) -> None:
|
| 451 |
+
descriptors = array.array("i", [descriptor])
|
| 452 |
+
channel.sendmsg(
|
| 453 |
+
[b"L"],
|
| 454 |
+
[(socket.SOL_SOCKET, socket.SCM_RIGHTS, descriptors.tobytes())],
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def _receive_fd(channel: socket.socket) -> int:
|
| 459 |
+
descriptors = array.array("i")
|
| 460 |
+
message, ancillary, _flags, _address = channel.recvmsg(
|
| 461 |
+
1, socket.CMSG_SPACE(descriptors.itemsize)
|
| 462 |
+
)
|
| 463 |
+
if message != b"L":
|
| 464 |
+
raise OSError(errno.EIO, "candidate sandbox listener was not delivered")
|
| 465 |
+
for level, kind, payload in ancillary:
|
| 466 |
+
if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
|
| 467 |
+
descriptors.frombytes(payload[: descriptors.itemsize])
|
| 468 |
+
return int(descriptors[0])
|
| 469 |
+
raise OSError(errno.EIO, "candidate sandbox listener fd is missing")
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def _tracee_process_id(thread_id: int) -> int:
|
| 473 |
+
try:
|
| 474 |
+
for line in Path(f"/proc/{thread_id}/status").read_text().splitlines():
|
| 475 |
+
if line.startswith("Tgid:"):
|
| 476 |
+
return int(line.partition(":")[2].strip())
|
| 477 |
+
except (OSError, ValueError):
|
| 478 |
+
pass
|
| 479 |
+
raise OSError(errno.ESRCH, "cannot identify candidate process")
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def _capture_worker_file(pid: int, descriptor: int, data: Path) -> int:
|
| 483 |
+
"""Atomically capture a regular data-dir inode from a tracee descriptor."""
|
| 484 |
+
|
| 485 |
+
captured = os.open(f"/proc/{pid}/fd/{descriptor}", os.O_RDWR | os.O_CLOEXEC)
|
| 486 |
+
try:
|
| 487 |
+
metadata = os.fstat(captured)
|
| 488 |
+
if not stat.S_ISREG(metadata.st_mode):
|
| 489 |
+
raise OSError(errno.EPERM, "candidate locks require a regular file")
|
| 490 |
+
target_text = os.readlink(f"/proc/self/fd/{captured}")
|
| 491 |
+
if target_text.endswith(" (deleted)"):
|
| 492 |
+
target_text = target_text[: -len(" (deleted)")]
|
| 493 |
+
target = Path(target_text).resolve()
|
| 494 |
+
if target != data and data not in target.parents:
|
| 495 |
+
raise OSError(errno.EPERM, "candidate lock target is outside data dir")
|
| 496 |
+
return captured
|
| 497 |
+
except BaseException:
|
| 498 |
+
os.close(captured)
|
| 499 |
+
raise
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def _read_tracee(pid: int, address: int, size: int) -> bytes:
|
| 503 |
+
descriptor = os.open(f"/proc/{pid}/mem", os.O_RDONLY | os.O_CLOEXEC)
|
| 504 |
+
try:
|
| 505 |
+
value = os.pread(descriptor, size, address)
|
| 506 |
+
finally:
|
| 507 |
+
os.close(descriptor)
|
| 508 |
+
if len(value) != size:
|
| 509 |
+
raise OSError(errno.EFAULT, "candidate fcntl argument is unreadable")
|
| 510 |
+
return value
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def _write_tracee(pid: int, address: int, value: bytes) -> None:
|
| 514 |
+
descriptor = os.open(f"/proc/{pid}/mem", os.O_WRONLY | os.O_CLOEXEC)
|
| 515 |
+
try:
|
| 516 |
+
written = os.pwrite(descriptor, value, address)
|
| 517 |
+
finally:
|
| 518 |
+
os.close(descriptor)
|
| 519 |
+
if written != len(value):
|
| 520 |
+
raise OSError(errno.EFAULT, "candidate fcntl result is unwritable")
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def _prune_closed_lock_files(
|
| 524 |
+
process_id: int,
|
| 525 |
+
locked_files: dict[tuple[int, int, int], int],
|
| 526 |
+
) -> None:
|
| 527 |
+
"""Release broker descriptors once the tracee has closed their inode.
|
| 528 |
+
|
| 529 |
+
SQLite creates and removes WAL/SHM files as short-lived connections come
|
| 530 |
+
and go. Keeping one broker descriptor for every historical inode pins both
|
| 531 |
+
deleted files and file descriptors until process exit, eventually turning
|
| 532 |
+
ordinary repeated requests into ``SQLITE_IOERR`` under ``RLIMIT_NOFILE``.
|
| 533 |
+
An OFD lock is no longer useful after the tracee has closed every descriptor
|
| 534 |
+
for that inode, so prune it before brokering the next lock operation.
|
| 535 |
+
"""
|
| 536 |
+
|
| 537 |
+
open_inodes: set[tuple[int, int]] = set()
|
| 538 |
+
try:
|
| 539 |
+
entries = list(Path(f"/proc/{process_id}/fd").iterdir())
|
| 540 |
+
except OSError:
|
| 541 |
+
return
|
| 542 |
+
for entry in entries:
|
| 543 |
+
try:
|
| 544 |
+
metadata = entry.stat()
|
| 545 |
+
except OSError:
|
| 546 |
+
continue
|
| 547 |
+
open_inodes.add((metadata.st_dev, metadata.st_ino))
|
| 548 |
+
for key, descriptor in list(locked_files.items()):
|
| 549 |
+
owner, device, inode = key
|
| 550 |
+
if owner == process_id and (device, inode) not in open_inodes:
|
| 551 |
+
os.close(descriptor)
|
| 552 |
+
del locked_files[key]
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def _broker_fcntl(
|
| 556 |
+
pid: int,
|
| 557 |
+
descriptor: int,
|
| 558 |
+
command: int,
|
| 559 |
+
argument: int,
|
| 560 |
+
data: Path,
|
| 561 |
+
locked_files: dict[tuple[int, int, int], int],
|
| 562 |
+
) -> int:
|
| 563 |
+
"""Execute a byte-range lock without continuing the untrusted syscall."""
|
| 564 |
+
|
| 565 |
+
process_id = _tracee_process_id(pid)
|
| 566 |
+
_prune_closed_lock_files(process_id, locked_files)
|
| 567 |
+
captured = _capture_worker_file(pid, descriptor, data)
|
| 568 |
+
metadata = os.fstat(captured)
|
| 569 |
+
key = (process_id, metadata.st_dev, metadata.st_ino)
|
| 570 |
+
broker_descriptor = locked_files.get(key)
|
| 571 |
+
if broker_descriptor is None:
|
| 572 |
+
locked_files[key] = captured
|
| 573 |
+
broker_descriptor = captured
|
| 574 |
+
else:
|
| 575 |
+
os.close(captured)
|
| 576 |
+
|
| 577 |
+
flock_value = bytearray(_read_tracee(pid, argument, 32))
|
| 578 |
+
# Linux requires l_pid to be zero for OFD lock operations. Classic
|
| 579 |
+
# F_SETLK callers do not own that output-only field, so normalize it when
|
| 580 |
+
# translating the request.
|
| 581 |
+
flock_value[24:28] = b"\0\0\0\0"
|
| 582 |
+
translations = {
|
| 583 |
+
5: 36, # F_GETLK -> F_OFD_GETLK
|
| 584 |
+
6: 37, # F_SETLK -> F_OFD_SETLK
|
| 585 |
+
7: 37, # F_SETLKW stays fail-fast so the broker cannot deadlock.
|
| 586 |
+
36: 36,
|
| 587 |
+
37: 37,
|
| 588 |
+
38: 37,
|
| 589 |
+
}
|
| 590 |
+
result = fcntl.fcntl(broker_descriptor, translations[command], bytes(flock_value))
|
| 591 |
+
if command in {5, 36}:
|
| 592 |
+
if not isinstance(result, bytes):
|
| 593 |
+
raise OSError(errno.EIO, "candidate lock query returned no structure")
|
| 594 |
+
_write_tracee(pid, argument, result.ljust(32, b"\0")[:32])
|
| 595 |
+
return 0
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def _lock_broker(listener: int, data: Path) -> None:
|
| 599 |
+
locked_files: dict[tuple[int, int, int], int] = {}
|
| 600 |
+
try:
|
| 601 |
+
while True:
|
| 602 |
+
request = bytearray(_SECCOMP_NOTIF_SIZE)
|
| 603 |
+
try:
|
| 604 |
+
fcntl.ioctl(listener, _SECCOMP_IOCTL_NOTIF_RECV, request, True)
|
| 605 |
+
except OSError as exc:
|
| 606 |
+
if exc.errno in {errno.EINTR, errno.ENOENT, errno.EBADF}:
|
| 607 |
+
if exc.errno == errno.EINTR:
|
| 608 |
+
continue
|
| 609 |
+
return
|
| 610 |
+
raise
|
| 611 |
+
unpacked = struct.unpack(_SECCOMP_NOTIF_FORMAT, request)
|
| 612 |
+
identifier, pid = int(unpacked[0]), int(unpacked[1])
|
| 613 |
+
try:
|
| 614 |
+
value = _broker_fcntl(
|
| 615 |
+
pid,
|
| 616 |
+
int(unpacked[6]),
|
| 617 |
+
int(unpacked[7]),
|
| 618 |
+
int(unpacked[8]),
|
| 619 |
+
data,
|
| 620 |
+
locked_files,
|
| 621 |
+
)
|
| 622 |
+
error = 0
|
| 623 |
+
except OSError as exc:
|
| 624 |
+
value = 0
|
| 625 |
+
error = -(exc.errno or errno.EPERM)
|
| 626 |
+
response = bytearray(
|
| 627 |
+
struct.pack(_SECCOMP_RESP_FORMAT, identifier, value, error, 0)
|
| 628 |
+
)
|
| 629 |
+
try:
|
| 630 |
+
fcntl.ioctl(listener, _SECCOMP_IOCTL_NOTIF_SEND, response, True)
|
| 631 |
+
except OSError as exc:
|
| 632 |
+
if exc.errno != errno.ENOENT:
|
| 633 |
+
raise
|
| 634 |
+
finally:
|
| 635 |
+
for descriptor in locked_files.values():
|
| 636 |
+
os.close(descriptor)
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def _drop_credentials(uid: int | None, gid: int | None) -> None:
|
| 640 |
+
"""Irreversibly adopt the requested worker identity, when configured."""
|
| 641 |
+
|
| 642 |
+
if uid is None or gid is None:
|
| 643 |
+
return
|
| 644 |
+
os.setgroups([])
|
| 645 |
+
os.setgid(gid)
|
| 646 |
+
os.setuid(uid)
|
| 647 |
+
if os.geteuid() != uid or os.getegid() != gid or os.getgroups():
|
| 648 |
+
raise OSError(errno.EPERM, "worker credential drop did not take effect")
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def _kill_and_reap(child_pid: int) -> None:
|
| 652 |
+
try:
|
| 653 |
+
os.kill(child_pid, signal.SIGKILL)
|
| 654 |
+
except ProcessLookupError:
|
| 655 |
+
pass
|
| 656 |
+
try:
|
| 657 |
+
os.waitpid(child_pid, 0)
|
| 658 |
+
except ChildProcessError:
|
| 659 |
+
pass
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def sandbox_exec(
|
| 663 |
+
command: Sequence[str],
|
| 664 |
+
*,
|
| 665 |
+
root: Path,
|
| 666 |
+
data: Path,
|
| 667 |
+
bind_port: int,
|
| 668 |
+
connect_ports: set[int],
|
| 669 |
+
uid: int | None,
|
| 670 |
+
gid: int | None,
|
| 671 |
+
file_size_limit_bytes: int | None,
|
| 672 |
+
read_paths: Sequence[Path] = (),
|
| 673 |
+
broker_tid_fd: int | None = None,
|
| 674 |
+
control_fd: int | None = None,
|
| 675 |
+
) -> None:
|
| 676 |
+
root = root.resolve(strict=True)
|
| 677 |
+
data = data.resolve(strict=True)
|
| 678 |
+
parent_channel, child_channel = socket.socketpair()
|
| 679 |
+
child_pid = os.fork()
|
| 680 |
+
if child_pid == 0:
|
| 681 |
+
parent_channel.close()
|
| 682 |
+
if control_fd is not None:
|
| 683 |
+
os.close(control_fd)
|
| 684 |
+
if broker_tid_fd is not None:
|
| 685 |
+
os.close(broker_tid_fd)
|
| 686 |
+
stage = "landlock"
|
| 687 |
+
try:
|
| 688 |
+
_landlock(root, data, bind_port, connect_ports, read_paths)
|
| 689 |
+
stage = "resource limits"
|
| 690 |
+
if file_size_limit_bytes is not None:
|
| 691 |
+
resource.setrlimit(
|
| 692 |
+
resource.RLIMIT_FSIZE,
|
| 693 |
+
(file_size_limit_bytes, file_size_limit_bytes),
|
| 694 |
+
)
|
| 695 |
+
if uid is not None and gid is not None:
|
| 696 |
+
stage = "credential drop"
|
| 697 |
+
_drop_credentials(uid, gid)
|
| 698 |
+
stage = "lock broker access"
|
| 699 |
+
libc = ctypes.CDLL(None, use_errno=True)
|
| 700 |
+
if libc.prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) != 0:
|
| 701 |
+
raise OSError(ctypes.get_errno(), "cannot enable lock broker access")
|
| 702 |
+
stage = "seccomp"
|
| 703 |
+
listener = _seccomp()
|
| 704 |
+
stage = "listener handoff"
|
| 705 |
+
_send_fd(child_channel, listener)
|
| 706 |
+
os.close(listener)
|
| 707 |
+
child_channel.close()
|
| 708 |
+
stage = "candidate cwd"
|
| 709 |
+
os.chdir(root)
|
| 710 |
+
stage = "candidate exec"
|
| 711 |
+
os.execv(command[0], list(command))
|
| 712 |
+
except BaseException as exc:
|
| 713 |
+
message = f"candidate sandbox setup failed during {stage}: {exc}\n".encode(
|
| 714 |
+
"utf-8", "replace"
|
| 715 |
+
)
|
| 716 |
+
try:
|
| 717 |
+
os.write(2, message)
|
| 718 |
+
except OSError:
|
| 719 |
+
pass
|
| 720 |
+
os._exit(126)
|
| 721 |
+
|
| 722 |
+
child_channel.close()
|
| 723 |
+
try:
|
| 724 |
+
listener = _receive_fd(parent_channel)
|
| 725 |
+
except BaseException:
|
| 726 |
+
_kill_and_reap(child_pid)
|
| 727 |
+
raise
|
| 728 |
+
finally:
|
| 729 |
+
parent_channel.close()
|
| 730 |
+
try:
|
| 731 |
+
_drop_credentials(uid, gid)
|
| 732 |
+
except BaseException:
|
| 733 |
+
os.close(listener)
|
| 734 |
+
_kill_and_reap(child_pid)
|
| 735 |
+
raise
|
| 736 |
+
broker_errors: list[BaseException] = []
|
| 737 |
+
if control_fd is not None:
|
| 738 |
+
os.set_blocking(control_fd, False)
|
| 739 |
+
|
| 740 |
+
def broker() -> None:
|
| 741 |
+
try:
|
| 742 |
+
_lock_broker(listener, data)
|
| 743 |
+
except BaseException as exc:
|
| 744 |
+
broker_errors.append(exc)
|
| 745 |
+
|
| 746 |
+
broker_thread = threading.Thread(target=broker, daemon=True)
|
| 747 |
+
broker_thread.start()
|
| 748 |
+
if broker_tid_fd is not None:
|
| 749 |
+
try:
|
| 750 |
+
native_id = broker_thread.native_id
|
| 751 |
+
if native_id is None:
|
| 752 |
+
raise OSError(errno.EIO, "lock broker thread has no native id")
|
| 753 |
+
os.write(
|
| 754 |
+
broker_tid_fd,
|
| 755 |
+
f"{native_id} {child_pid}\n".encode("ascii"),
|
| 756 |
+
)
|
| 757 |
+
except BaseException:
|
| 758 |
+
os.close(listener)
|
| 759 |
+
_kill_and_reap(child_pid)
|
| 760 |
+
broker_thread.join(timeout=1)
|
| 761 |
+
if control_fd is not None:
|
| 762 |
+
os.close(control_fd)
|
| 763 |
+
raise
|
| 764 |
+
finally:
|
| 765 |
+
os.close(broker_tid_fd)
|
| 766 |
+
status = 0
|
| 767 |
+
while True:
|
| 768 |
+
if control_fd is not None:
|
| 769 |
+
try:
|
| 770 |
+
requested = os.read(control_fd, 4096)
|
| 771 |
+
except (BlockingIOError, OSError):
|
| 772 |
+
requested = b""
|
| 773 |
+
for marker in requested:
|
| 774 |
+
requested_signal = {
|
| 775 |
+
ord("T"): signal.SIGTERM,
|
| 776 |
+
ord("K"): signal.SIGKILL,
|
| 777 |
+
}.get(marker)
|
| 778 |
+
if requested_signal is not None:
|
| 779 |
+
try:
|
| 780 |
+
os.kill(child_pid, requested_signal)
|
| 781 |
+
except ProcessLookupError:
|
| 782 |
+
pass
|
| 783 |
+
waited, status = os.waitpid(child_pid, os.WNOHANG)
|
| 784 |
+
if waited == child_pid:
|
| 785 |
+
break
|
| 786 |
+
if broker_errors:
|
| 787 |
+
os.kill(child_pid, signal.SIGKILL)
|
| 788 |
+
_waited, status = os.waitpid(child_pid, 0)
|
| 789 |
+
break
|
| 790 |
+
time.sleep(0.01)
|
| 791 |
+
if control_fd is not None:
|
| 792 |
+
os.close(control_fd)
|
| 793 |
+
os.close(listener)
|
| 794 |
+
broker_thread.join(timeout=1)
|
| 795 |
+
if broker_errors:
|
| 796 |
+
raise OSError(errno.EIO, "candidate lock broker failed") from broker_errors[0]
|
| 797 |
+
# The trusted launcher/broker completed normally. Candidate business exit
|
| 798 |
+
# status is observed through readiness/lifecycle, while a nonzero launcher
|
| 799 |
+
# status remains reserved for audit infrastructure failure.
|
| 800 |
+
os._exit(0)
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
def main(argv: Sequence[str] | None = None) -> int:
|
| 804 |
+
parser = argparse.ArgumentParser()
|
| 805 |
+
parser.add_argument("--root", type=Path, required=True)
|
| 806 |
+
parser.add_argument("--data", type=Path, required=True)
|
| 807 |
+
parser.add_argument("--bind-port", type=int, required=True)
|
| 808 |
+
parser.add_argument("--connect-port", type=int, action="append", default=[])
|
| 809 |
+
parser.add_argument("--uid", type=int)
|
| 810 |
+
parser.add_argument("--gid", type=int)
|
| 811 |
+
parser.add_argument("--file-size-limit-bytes", type=int)
|
| 812 |
+
parser.add_argument("--read-path", type=Path, action="append", default=[])
|
| 813 |
+
parser.add_argument("--broker-tid-fd", type=int)
|
| 814 |
+
parser.add_argument("--control-fd", type=int)
|
| 815 |
+
parser.add_argument("command", nargs=argparse.REMAINDER)
|
| 816 |
+
arguments = parser.parse_args(argv)
|
| 817 |
+
command = arguments.command
|
| 818 |
+
if command[:1] == ["--"]:
|
| 819 |
+
command = command[1:]
|
| 820 |
+
if not command:
|
| 821 |
+
parser.error("candidate command is required")
|
| 822 |
+
if (arguments.uid is None) != (arguments.gid is None):
|
| 823 |
+
parser.error("uid and gid must be provided together")
|
| 824 |
+
sandbox_exec(
|
| 825 |
+
command,
|
| 826 |
+
root=arguments.root,
|
| 827 |
+
data=arguments.data,
|
| 828 |
+
bind_port=arguments.bind_port,
|
| 829 |
+
connect_ports=set(arguments.connect_port),
|
| 830 |
+
uid=arguments.uid,
|
| 831 |
+
gid=arguments.gid,
|
| 832 |
+
file_size_limit_bytes=arguments.file_size_limit_bytes,
|
| 833 |
+
read_paths=arguments.read_path,
|
| 834 |
+
broker_tid_fd=arguments.broker_tid_fd,
|
| 835 |
+
control_fd=arguments.control_fd,
|
| 836 |
+
)
|
| 837 |
+
return 127
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
if __name__ == "__main__":
|
| 841 |
+
raise SystemExit(main())
|
tasks/columbia/environment/reference/clone/static/assets/cms/0907-launch_UShomepageOG.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/10-27_COL_US_EFWtest2_HP_Storytelling_Card1.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/10-27_COL_US_EFWtest2_HP_Storytelling_Card2.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/10-27_COL_US_EFWtest2_HP_Storytelling_Card3.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/10-27_COL_US_EFWtest2_HP_Storytelling_Card5.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/10-27_COL_US_EFWtest2_HP_Storytelling_Hero.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/12-23_CGR_Logo.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2181437_C_NA_HP_StorytellingComponent_Card4_v4.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2279348_COL_US_Q1-Q2_SpringSummer_NewArrivals_Visnav_Infant.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2279348_COL_US_Q1-Q2_SpringSummer_NewArrivals_Visnav_Mens_Shirts.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2308014_CA_Jackets_Mens_VisNav_Slot04.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2308014_US_Supergrid_TopLevel_Equip_VisNav_Slot01.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2308014_US_Supergrid_TopLevel_Equip_VisNav_Slot02.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2308014_US_Supergrid_TopLevel_Equip_VisNav_Slot03.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2308014_US_Supergrid_TopLevel_Equip_VisNav_Slot04.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_ACE.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Bottoms.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Dresses.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Girls.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Jackets.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Shoes.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_NA_May_Visnavs_NewArrivals_Tops.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_BigTall.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_Boys.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_K_Shoes.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_M_Shoes.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_MensACE.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_MensBottoms.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_MensShoes.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_Toddlers_v2.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/2500648_C_US_May_Visnavs_NewArrivals_W_Shoes.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_NA_August_VisNavBanners_CampingGear.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_NA_August_VisNavBanners_Drinkware.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Beanie.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Belts.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Booney.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Gaiters.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Hats.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/250731_beta_2124148_COL_US_Visnav_Ace_Socks.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/6-30_COL_US_S26_HP_SummerTech_M_Subhero.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/7-30_COL_CA_S26_HP_Run_Subhero.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/8-10_2686468_COL_US_HP_AmazeSweats_Subhero.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/8-10_2686468_COL_US_HP_FallNA_DG_Subhero.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/8-10_ROC_MomensBan_DG.webp
ADDED
|
Git LFS Details
|
tasks/columbia/environment/reference/clone/static/assets/cms/8-27_COL_US_HP_We_Heart_AmazePuff_Style_Subhero_v2.webp
ADDED
|
Git LFS Details
|