Spaces:
Running
Running
fix: record content qualification timing
Browse files- scripts/build_release.py +38 -7
- scripts/run_content_matrix.py +118 -0
- scripts/smoke_content_ai.py +115 -24
- scripts/verify_release.py +61 -10
- src/lumi_eggcracker/artifacts.py +16 -3
- src/lumi_eggcracker/detectors.py +46 -11
- src/lumi_eggcracker/discovery.py +26 -7
- src/lumi_eggcracker/elfmarkers.py +62 -11
- src/lumi_eggcracker/observation.py +8 -2
- src/lumi_eggcracker/supervisor.py +357 -44
- tests/test_artifacts.py +6 -2
- tests/test_detectors.py +17 -4
- tests/test_elfmarkers.py +13 -5
scripts/build_release.py
CHANGED
|
@@ -53,14 +53,44 @@ def main() -> int:
|
|
| 53 |
bundle = args.output / f"lumi-eggcracker-{release_version}-linux.zip"
|
| 54 |
with tempfile.TemporaryDirectory(prefix="lumi-eggcracker-build-") as raw:
|
| 55 |
stage = Path(raw) / "src"
|
| 56 |
-
shutil.copytree(
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
zipapp.create_archive(stage, target=artifact, interpreter="/usr/bin/env python3")
|
| 60 |
-
command(
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
prefix = f"lumi-eggcracker-{release_version}"
|
| 65 |
release_files = {
|
| 66 |
artifact: artifact.name,
|
|
@@ -82,6 +112,7 @@ def main() -> int:
|
|
| 82 |
ROOT / "scripts" / "smoke_local_ai.py": "scripts/smoke_local_ai.py",
|
| 83 |
ROOT / "scripts" / "smoke_autonomous_ai.py": "scripts/smoke_autonomous_ai.py",
|
| 84 |
ROOT / "scripts" / "smoke_content_ai.py": "scripts/smoke_content_ai.py",
|
|
|
|
| 85 |
ROOT / "scripts" / "run_autonomous_matrix.py": "scripts/run_autonomous_matrix.py",
|
| 86 |
}
|
| 87 |
with zipfile.ZipFile(bundle, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
|
|
|
|
| 53 |
bundle = args.output / f"lumi-eggcracker-{release_version}-linux.zip"
|
| 54 |
with tempfile.TemporaryDirectory(prefix="lumi-eggcracker-build-") as raw:
|
| 55 |
stage = Path(raw) / "src"
|
| 56 |
+
shutil.copytree(
|
| 57 |
+
ROOT / "src", stage, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.egg-info")
|
| 58 |
+
)
|
| 59 |
+
(stage / "__main__.py").write_text(
|
| 60 |
+
"from lumi_eggcracker.cli import main\nraise SystemExit(main())\n", encoding="utf-8"
|
| 61 |
+
)
|
| 62 |
+
(stage / "lumi_eggcracker" / "build_info.py").write_text(
|
| 63 |
+
f'SOURCE_COMMIT = "{commit}"\n', encoding="utf-8"
|
| 64 |
+
)
|
| 65 |
zipapp.create_archive(stage, target=artifact, interpreter="/usr/bin/env python3")
|
| 66 |
+
command(
|
| 67 |
+
[
|
| 68 |
+
"git",
|
| 69 |
+
"-C",
|
| 70 |
+
str(ROOT),
|
| 71 |
+
"archive",
|
| 72 |
+
"--format=zip",
|
| 73 |
+
f"--prefix=lumi-eggcracker-{release_version}/",
|
| 74 |
+
"-o",
|
| 75 |
+
str(source),
|
| 76 |
+
"HEAD",
|
| 77 |
+
]
|
| 78 |
+
)
|
| 79 |
+
manifest = {
|
| 80 |
+
"artifact": artifact.name,
|
| 81 |
+
"sha256": digest(artifact),
|
| 82 |
+
"source_archive": source.name,
|
| 83 |
+
"source_archive_sha256": digest(source),
|
| 84 |
+
"source_commit": commit,
|
| 85 |
+
"version": release_version,
|
| 86 |
+
}
|
| 87 |
+
(args.output / "release-manifest.json").write_text(
|
| 88 |
+
__import__("json").dumps(manifest, sort_keys=True) + "\n", encoding="utf-8"
|
| 89 |
+
)
|
| 90 |
+
(args.output / "SHA256SUMS").write_text(
|
| 91 |
+
f"{manifest['sha256']} {artifact.name}\n{manifest['source_archive_sha256']} {source.name}\n",
|
| 92 |
+
encoding="utf-8",
|
| 93 |
+
)
|
| 94 |
prefix = f"lumi-eggcracker-{release_version}"
|
| 95 |
release_files = {
|
| 96 |
artifact: artifact.name,
|
|
|
|
| 112 |
ROOT / "scripts" / "smoke_local_ai.py": "scripts/smoke_local_ai.py",
|
| 113 |
ROOT / "scripts" / "smoke_autonomous_ai.py": "scripts/smoke_autonomous_ai.py",
|
| 114 |
ROOT / "scripts" / "smoke_content_ai.py": "scripts/smoke_content_ai.py",
|
| 115 |
+
ROOT / "scripts" / "run_content_matrix.py": "scripts/run_content_matrix.py",
|
| 116 |
ROOT / "scripts" / "run_autonomous_matrix.py": "scripts/run_autonomous_matrix.py",
|
| 117 |
}
|
| 118 |
with zipfile.ZipFile(bundle, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
|
scripts/run_content_matrix.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the 100-case renamed, extensionless real-AI content-recognition matrix."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import secrets
|
| 9 |
+
import shutil
|
| 10 |
+
import subprocess
|
| 11 |
+
import tempfile
|
| 12 |
+
import time
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
from smoke_content_ai import assets, command, launch, receipt_after, stop
|
| 16 |
+
|
| 17 |
+
DETECTIONS = Path("/var/lib/lumi-eggcracker/detections")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def percentile(values: list[float], point: int) -> float:
|
| 21 |
+
if not values:
|
| 22 |
+
raise RuntimeError("empty latency distribution")
|
| 23 |
+
ordered = sorted(values)
|
| 24 |
+
return ordered[min(len(ordered) - 1, (len(ordered) * point + 99) // 100 - 1)]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main() -> int:
|
| 28 |
+
if os.geteuid() != 0:
|
| 29 |
+
raise SystemExit("content matrix must run as root")
|
| 30 |
+
parser = argparse.ArgumentParser()
|
| 31 |
+
parser.add_argument("--assets-manifest", required=True, type=Path)
|
| 32 |
+
parser.add_argument("--user", required=True)
|
| 33 |
+
parser.add_argument("--repetitions", type=int, default=100)
|
| 34 |
+
parser.add_argument("--output", required=True, type=Path)
|
| 35 |
+
args = parser.parse_args()
|
| 36 |
+
if (
|
| 37 |
+
args.repetitions != 100
|
| 38 |
+
or args.output.exists()
|
| 39 |
+
or args.output.is_symlink()
|
| 40 |
+
or not args.output.parent.is_dir()
|
| 41 |
+
):
|
| 42 |
+
raise SystemExit("output must be new and repetitions must equal 100")
|
| 43 |
+
results: dict[str, object] = {"canary_survivals": 0, "kills": 0, "result": "FAIL"}
|
| 44 |
+
try:
|
| 45 |
+
runner, model, _manifest = assets(args.assets_manifest)
|
| 46 |
+
starts: list[float] = []
|
| 47 |
+
qualification: list[float] = []
|
| 48 |
+
empties: list[float] = []
|
| 49 |
+
with tempfile.TemporaryDirectory(prefix="lumi-content-matrix-", dir="/tmp") as raw:
|
| 50 |
+
root = Path(raw)
|
| 51 |
+
os.chmod(root, 0o755)
|
| 52 |
+
disguised_runner = root / secrets.token_hex(12)
|
| 53 |
+
disguised_model = root / secrets.token_hex(12)
|
| 54 |
+
wrapper = root / f"{secrets.token_hex(8)}.py"
|
| 55 |
+
shutil.copyfile(runner, disguised_runner)
|
| 56 |
+
os.chmod(disguised_runner, 0o755)
|
| 57 |
+
try:
|
| 58 |
+
os.link(model, disguised_model)
|
| 59 |
+
except OSError:
|
| 60 |
+
shutil.copyfile(model, disguised_model)
|
| 61 |
+
wrapper.write_text(
|
| 62 |
+
"import os,sys\nos.execv(sys.argv[1], sys.argv[1:])\n", encoding="utf-8"
|
| 63 |
+
)
|
| 64 |
+
argv = command(disguised_runner, disguised_model)
|
| 65 |
+
if any(item.endswith(".gguf") for item in argv):
|
| 66 |
+
raise RuntimeError("matrix invocation accidentally exposes a model suffix")
|
| 67 |
+
for _ in range(args.repetitions):
|
| 68 |
+
canary = subprocess.Popen(["/bin/sleep", "30"], start_new_session=True)
|
| 69 |
+
process: subprocess.Popen[bytes] | None = None
|
| 70 |
+
try:
|
| 71 |
+
before = set(DETECTIONS.glob("*.json"))
|
| 72 |
+
started = time.monotonic_ns()
|
| 73 |
+
process = launch(args.user, wrapper, argv, root / "out")
|
| 74 |
+
receipt = receipt_after(before)
|
| 75 |
+
stop(process)
|
| 76 |
+
process = None
|
| 77 |
+
if (
|
| 78 |
+
receipt.get("detector", {}).get("profile") != "content.gguf-llama"
|
| 79 |
+
or receipt.get("detector", {}).get("detection_path") != "CONTENT"
|
| 80 |
+
or canary.poll() is not None
|
| 81 |
+
or receipt.get("containment", {}).get("surviving_pids")
|
| 82 |
+
):
|
| 83 |
+
raise RuntimeError("content containment or canary proof failed")
|
| 84 |
+
starts.append(
|
| 85 |
+
(receipt["containment"]["first_stop_monotonic_ns"] - started) / 1_000_000
|
| 86 |
+
)
|
| 87 |
+
qualification.append(
|
| 88 |
+
float(receipt["containment"]["qualification_to_first_stop_ms"])
|
| 89 |
+
)
|
| 90 |
+
empties.append(float(receipt["containment"]["trigger_to_empty_ms"]))
|
| 91 |
+
results["kills"] = int(results["kills"]) + 1
|
| 92 |
+
results["canary_survivals"] = int(results["canary_survivals"]) + 1
|
| 93 |
+
finally:
|
| 94 |
+
stop(process)
|
| 95 |
+
stop(canary)
|
| 96 |
+
if (
|
| 97 |
+
percentile(starts, 95) >= 1000
|
| 98 |
+
or percentile(qualification, 95) >= 100
|
| 99 |
+
or percentile(empties, 95) >= 500
|
| 100 |
+
):
|
| 101 |
+
raise RuntimeError("content latency gate failed")
|
| 102 |
+
results["latency_ms"] = {
|
| 103 |
+
"process_start_to_first_stop_p95": percentile(starts, 95),
|
| 104 |
+
"qualification_to_first_stop_p95": percentile(qualification, 95),
|
| 105 |
+
"trigger_to_empty_p95": percentile(empties, 95),
|
| 106 |
+
}
|
| 107 |
+
results["result"] = "PASS"
|
| 108 |
+
args.output.write_text(json.dumps(results, sort_keys=True) + "\n", encoding="utf-8")
|
| 109 |
+
return 0
|
| 110 |
+
except (OSError, RuntimeError, TypeError, json.JSONDecodeError) as error:
|
| 111 |
+
results["error"] = str(error)
|
| 112 |
+
if not args.output.exists():
|
| 113 |
+
args.output.write_text(json.dumps(results, sort_keys=True) + "\n", encoding="utf-8")
|
| 114 |
+
raise SystemExit(f"content matrix failed: {error}") from error
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
if __name__ == "__main__":
|
| 118 |
+
raise SystemExit(main())
|
scripts/smoke_content_ai.py
CHANGED
|
@@ -31,10 +31,15 @@ def digest(path: Path) -> str:
|
|
| 31 |
|
| 32 |
def assets(path: Path) -> tuple[Path, Path, dict[str, Any]]:
|
| 33 |
value = json.loads(path.read_text(encoding="utf-8"))
|
| 34 |
-
if
|
|
|
|
|
|
|
|
|
|
| 35 |
raise RuntimeError("asset manifest is invalid")
|
| 36 |
runner, model = Path(value["llama"]["path"]), Path(value["model"]["path"])
|
| 37 |
-
if any(item.is_symlink() or not item.is_file() for item in (runner, model)) or not os.access(
|
|
|
|
|
|
|
| 38 |
raise RuntimeError("AI smoke assets are invalid")
|
| 39 |
if digest(runner) != value["llama"]["sha256"] or digest(model) != value["model"]["sha256"]:
|
| 40 |
raise RuntimeError("AI smoke asset digest differs from manifest")
|
|
@@ -42,9 +47,17 @@ def assets(path: Path) -> tuple[Path, Path, dict[str, Any]]:
|
|
| 42 |
|
| 43 |
|
| 44 |
def control(user: str, argv: list[str]) -> dict[str, Any]:
|
| 45 |
-
result = subprocess.run(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
if result.returncode:
|
| 47 |
-
raise RuntimeError(
|
|
|
|
|
|
|
| 48 |
value = json.loads(result.stdout)
|
| 49 |
if not isinstance(value, dict):
|
| 50 |
raise TypeError("Eggcracker control command returned invalid JSON")
|
|
@@ -62,16 +75,40 @@ def receipt_after(before: set[Path], *, timeout: float = 90) -> dict[str, Any]:
|
|
| 62 |
while time.monotonic() < deadline:
|
| 63 |
paths = set(DETECTIONS.glob("*.json")) - before
|
| 64 |
if paths:
|
| 65 |
-
value = json.loads(
|
|
|
|
|
|
|
| 66 |
if value.get("result") != "TERMINATED":
|
| 67 |
-
raise RuntimeError(
|
|
|
|
|
|
|
| 68 |
return value
|
| 69 |
time.sleep(0.02)
|
| 70 |
raise RuntimeError("content detection receipt did not appear")
|
| 71 |
|
| 72 |
|
| 73 |
def command(runner: Path, model: Path) -> list[str]:
|
| 74 |
-
return [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
|
| 77 |
def launch(user: str, wrapper: Path, argv: list[str], output: Path) -> subprocess.Popen[bytes]:
|
|
@@ -79,26 +116,37 @@ def launch(user: str, wrapper: Path, argv: list[str], output: Path) -> subproces
|
|
| 79 |
try:
|
| 80 |
# The wrapper is deliberately unfamiliar and replaces itself; the
|
| 81 |
# observed executable/argv0 is a copied random filename, not Python.
|
| 82 |
-
return subprocess.Popen(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
finally:
|
| 84 |
handle.close()
|
| 85 |
|
| 86 |
|
| 87 |
def one(runner: Path, model: Path, user: str, index: int) -> dict[str, Any]:
|
| 88 |
with tempfile.TemporaryDirectory(prefix="lumi-content-smoke-", dir="/tmp") as raw:
|
| 89 |
-
root = Path(raw)
|
|
|
|
| 90 |
disguised_runner = root / secrets.token_hex(12)
|
| 91 |
disguised_model = root / secrets.token_hex(12)
|
| 92 |
wrapper = root / f"{secrets.token_hex(8)}.py"
|
| 93 |
output = root / "out"
|
| 94 |
-
shutil.copyfile(runner, disguised_runner)
|
|
|
|
| 95 |
try:
|
| 96 |
os.link(model, disguised_model)
|
| 97 |
except OSError:
|
| 98 |
shutil.copyfile(model, disguised_model)
|
| 99 |
wrapper.write_text("import os,sys\nos.execv(sys.argv[1], sys.argv[1:])\n", encoding="utf-8")
|
| 100 |
final_argv = command(disguised_runner, disguised_model)
|
| 101 |
-
if any(item.endswith(".gguf") for item in final_argv) or disguised_runner.name in {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
raise RuntimeError("content smoke accidentally satisfies a fast-name condition")
|
| 103 |
canary = subprocess.Popen(["/bin/sleep", "180"], start_new_session=True)
|
| 104 |
unapproved: subprocess.Popen[bytes] | None = None
|
|
@@ -108,32 +156,64 @@ def one(runner: Path, model: Path, user: str, index: int) -> dict[str, Any]:
|
|
| 108 |
before = set(DETECTIONS.glob("*.json"))
|
| 109 |
unapproved = launch(user, wrapper, final_argv, output)
|
| 110 |
first = receipt_after(before)
|
| 111 |
-
stop(unapproved)
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
raise RuntimeError("content profile or canary proof failed")
|
| 114 |
-
if str(disguised_model) in json.dumps(first, sort_keys=True) or str(
|
|
|
|
|
|
|
| 115 |
raise RuntimeError("content receipt leaked a local model or wrapper path")
|
| 116 |
-
approved = control(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
if approved.get("result") != "APPROVED":
|
| 118 |
raise RuntimeError("exact content approval failed")
|
| 119 |
allowed = launch(user, wrapper, final_argv, output)
|
| 120 |
deadline = time.monotonic() + 120
|
| 121 |
-
while time.monotonic() < deadline and (
|
|
|
|
|
|
|
| 122 |
time.sleep(0.05)
|
| 123 |
if allowed.poll() is not None or output.stat().st_size < 32:
|
| 124 |
raise RuntimeError("approved disguised AI did not produce output")
|
| 125 |
generated = output.stat().st_size
|
| 126 |
-
stop(allowed)
|
|
|
|
| 127 |
control(user, ["revoke", "--name", name])
|
| 128 |
before = set(DETECTIONS.glob("*.json"))
|
| 129 |
unapproved = launch(user, wrapper, final_argv, output)
|
| 130 |
second = receipt_after(before)
|
| 131 |
-
stop(unapproved)
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
raise RuntimeError("revoked disguised AI was not terminated")
|
| 134 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
finally:
|
| 136 |
-
stop(unapproved)
|
|
|
|
|
|
|
| 137 |
|
| 138 |
|
| 139 |
def main() -> int:
|
|
@@ -145,17 +225,28 @@ def main() -> int:
|
|
| 145 |
parser.add_argument("--repetitions", required=True, type=int)
|
| 146 |
parser.add_argument("--output", required=True, type=Path)
|
| 147 |
args = parser.parse_args()
|
| 148 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
raise SystemExit("output must be new and repetitions must equal five")
|
| 150 |
try:
|
| 151 |
pwd.getpwnam(args.user)
|
| 152 |
runner, model, _manifest = assets(args.assets_manifest)
|
| 153 |
values = [one(runner, model, args.user, index) for index in range(args.repetitions)]
|
| 154 |
-
args.output.write_text(
|
|
|
|
|
|
|
|
|
|
| 155 |
return 0
|
| 156 |
except (OSError, RuntimeError, TypeError, json.JSONDecodeError) as error:
|
| 157 |
if not args.output.exists():
|
| 158 |
-
args.output.write_text(
|
|
|
|
|
|
|
|
|
|
| 159 |
raise SystemExit(f"content AI smoke failed: {error}") from error
|
| 160 |
|
| 161 |
|
|
|
|
| 31 |
|
| 32 |
def assets(path: Path) -> tuple[Path, Path, dict[str, Any]]:
|
| 33 |
value = json.loads(path.read_text(encoding="utf-8"))
|
| 34 |
+
if (
|
| 35 |
+
set(value) != {"llama", "model", "platform", "schema_version"}
|
| 36 |
+
or value["schema_version"] != ASSET_SCHEMA
|
| 37 |
+
):
|
| 38 |
raise RuntimeError("asset manifest is invalid")
|
| 39 |
runner, model = Path(value["llama"]["path"]), Path(value["model"]["path"])
|
| 40 |
+
if any(item.is_symlink() or not item.is_file() for item in (runner, model)) or not os.access(
|
| 41 |
+
runner, os.X_OK
|
| 42 |
+
):
|
| 43 |
raise RuntimeError("AI smoke assets are invalid")
|
| 44 |
if digest(runner) != value["llama"]["sha256"] or digest(model) != value["model"]["sha256"]:
|
| 45 |
raise RuntimeError("AI smoke asset digest differs from manifest")
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
def control(user: str, argv: list[str]) -> dict[str, Any]:
|
| 50 |
+
result = subprocess.run(
|
| 51 |
+
["/usr/sbin/runuser", "-u", user, "--", CLI, *argv],
|
| 52 |
+
capture_output=True,
|
| 53 |
+
text=True,
|
| 54 |
+
check=False,
|
| 55 |
+
timeout=30,
|
| 56 |
+
)
|
| 57 |
if result.returncode:
|
| 58 |
+
raise RuntimeError(
|
| 59 |
+
result.stderr.strip() or result.stdout.strip() or "Eggcracker control command failed"
|
| 60 |
+
)
|
| 61 |
value = json.loads(result.stdout)
|
| 62 |
if not isinstance(value, dict):
|
| 63 |
raise TypeError("Eggcracker control command returned invalid JSON")
|
|
|
|
| 75 |
while time.monotonic() < deadline:
|
| 76 |
paths = set(DETECTIONS.glob("*.json")) - before
|
| 77 |
if paths:
|
| 78 |
+
value = json.loads(
|
| 79 |
+
max(paths, key=lambda item: item.stat().st_mtime_ns).read_text(encoding="utf-8")
|
| 80 |
+
)
|
| 81 |
if value.get("result") != "TERMINATED":
|
| 82 |
+
raise RuntimeError(
|
| 83 |
+
f"content containment failed: {value.get('error', value.get('result'))}"
|
| 84 |
+
)
|
| 85 |
return value
|
| 86 |
time.sleep(0.02)
|
| 87 |
raise RuntimeError("content detection receipt did not appear")
|
| 88 |
|
| 89 |
|
| 90 |
def command(runner: Path, model: Path) -> list[str]:
|
| 91 |
+
return [
|
| 92 |
+
str(runner),
|
| 93 |
+
"-m",
|
| 94 |
+
str(model),
|
| 95 |
+
"-p",
|
| 96 |
+
"Name a Linux cgroup property.",
|
| 97 |
+
"-n",
|
| 98 |
+
"4096",
|
| 99 |
+
"-t",
|
| 100 |
+
"12",
|
| 101 |
+
"-tb",
|
| 102 |
+
"12",
|
| 103 |
+
"-c",
|
| 104 |
+
"512",
|
| 105 |
+
"--simple-io",
|
| 106 |
+
"--single-turn",
|
| 107 |
+
"--no-warmup",
|
| 108 |
+
"--no-display-prompt",
|
| 109 |
+
"--seed",
|
| 110 |
+
"1234",
|
| 111 |
+
]
|
| 112 |
|
| 113 |
|
| 114 |
def launch(user: str, wrapper: Path, argv: list[str], output: Path) -> subprocess.Popen[bytes]:
|
|
|
|
| 116 |
try:
|
| 117 |
# The wrapper is deliberately unfamiliar and replaces itself; the
|
| 118 |
# observed executable/argv0 is a copied random filename, not Python.
|
| 119 |
+
return subprocess.Popen(
|
| 120 |
+
["/usr/sbin/runuser", "-u", user, "--", "/usr/bin/python3", str(wrapper), *argv],
|
| 121 |
+
stdout=handle,
|
| 122 |
+
stderr=subprocess.DEVNULL,
|
| 123 |
+
start_new_session=True,
|
| 124 |
+
)
|
| 125 |
finally:
|
| 126 |
handle.close()
|
| 127 |
|
| 128 |
|
| 129 |
def one(runner: Path, model: Path, user: str, index: int) -> dict[str, Any]:
|
| 130 |
with tempfile.TemporaryDirectory(prefix="lumi-content-smoke-", dir="/tmp") as raw:
|
| 131 |
+
root = Path(raw)
|
| 132 |
+
os.chmod(root, 0o755)
|
| 133 |
disguised_runner = root / secrets.token_hex(12)
|
| 134 |
disguised_model = root / secrets.token_hex(12)
|
| 135 |
wrapper = root / f"{secrets.token_hex(8)}.py"
|
| 136 |
output = root / "out"
|
| 137 |
+
shutil.copyfile(runner, disguised_runner)
|
| 138 |
+
os.chmod(disguised_runner, 0o755)
|
| 139 |
try:
|
| 140 |
os.link(model, disguised_model)
|
| 141 |
except OSError:
|
| 142 |
shutil.copyfile(model, disguised_model)
|
| 143 |
wrapper.write_text("import os,sys\nos.execv(sys.argv[1], sys.argv[1:])\n", encoding="utf-8")
|
| 144 |
final_argv = command(disguised_runner, disguised_model)
|
| 145 |
+
if any(item.endswith(".gguf") for item in final_argv) or disguised_runner.name in {
|
| 146 |
+
"llama-cli",
|
| 147 |
+
"llama-server",
|
| 148 |
+
"main",
|
| 149 |
+
}:
|
| 150 |
raise RuntimeError("content smoke accidentally satisfies a fast-name condition")
|
| 151 |
canary = subprocess.Popen(["/bin/sleep", "180"], start_new_session=True)
|
| 152 |
unapproved: subprocess.Popen[bytes] | None = None
|
|
|
|
| 156 |
before = set(DETECTIONS.glob("*.json"))
|
| 157 |
unapproved = launch(user, wrapper, final_argv, output)
|
| 158 |
first = receipt_after(before)
|
| 159 |
+
stop(unapproved)
|
| 160 |
+
unapproved = None
|
| 161 |
+
if (
|
| 162 |
+
first.get("detector", {}).get("profile") != "content.gguf-llama"
|
| 163 |
+
or first.get("detector", {}).get("detection_path") != "CONTENT"
|
| 164 |
+
or canary.poll() is not None
|
| 165 |
+
):
|
| 166 |
raise RuntimeError("content profile or canary proof failed")
|
| 167 |
+
if str(disguised_model) in json.dumps(first, sort_keys=True) or str(
|
| 168 |
+
wrapper
|
| 169 |
+
) in json.dumps(first, sort_keys=True):
|
| 170 |
raise RuntimeError("content receipt leaked a local model or wrapper path")
|
| 171 |
+
approved = control(
|
| 172 |
+
user,
|
| 173 |
+
[
|
| 174 |
+
"approve",
|
| 175 |
+
"--name",
|
| 176 |
+
name,
|
| 177 |
+
"--uid",
|
| 178 |
+
str(pwd.getpwnam(user).pw_uid),
|
| 179 |
+
"--",
|
| 180 |
+
*final_argv,
|
| 181 |
+
],
|
| 182 |
+
)
|
| 183 |
if approved.get("result") != "APPROVED":
|
| 184 |
raise RuntimeError("exact content approval failed")
|
| 185 |
allowed = launch(user, wrapper, final_argv, output)
|
| 186 |
deadline = time.monotonic() + 120
|
| 187 |
+
while time.monotonic() < deadline and (
|
| 188 |
+
not output.is_file() or output.stat().st_size < 32
|
| 189 |
+
):
|
| 190 |
time.sleep(0.05)
|
| 191 |
if allowed.poll() is not None or output.stat().st_size < 32:
|
| 192 |
raise RuntimeError("approved disguised AI did not produce output")
|
| 193 |
generated = output.stat().st_size
|
| 194 |
+
stop(allowed)
|
| 195 |
+
allowed = None
|
| 196 |
control(user, ["revoke", "--name", name])
|
| 197 |
before = set(DETECTIONS.glob("*.json"))
|
| 198 |
unapproved = launch(user, wrapper, final_argv, output)
|
| 199 |
second = receipt_after(before)
|
| 200 |
+
stop(unapproved)
|
| 201 |
+
unapproved = None
|
| 202 |
+
if (
|
| 203 |
+
second.get("detector", {}).get("profile") != "content.gguf-llama"
|
| 204 |
+
or canary.poll() is not None
|
| 205 |
+
):
|
| 206 |
raise RuntimeError("revoked disguised AI was not terminated")
|
| 207 |
+
return {
|
| 208 |
+
"approved_generated_bytes": generated,
|
| 209 |
+
"first_receipt": first,
|
| 210 |
+
"result": "PASS",
|
| 211 |
+
"second_receipt": second,
|
| 212 |
+
}
|
| 213 |
finally:
|
| 214 |
+
stop(unapproved)
|
| 215 |
+
stop(allowed)
|
| 216 |
+
stop(canary)
|
| 217 |
|
| 218 |
|
| 219 |
def main() -> int:
|
|
|
|
| 225 |
parser.add_argument("--repetitions", required=True, type=int)
|
| 226 |
parser.add_argument("--output", required=True, type=Path)
|
| 227 |
args = parser.parse_args()
|
| 228 |
+
if (
|
| 229 |
+
args.repetitions != 5
|
| 230 |
+
or args.output.exists()
|
| 231 |
+
or args.output.is_symlink()
|
| 232 |
+
or not args.output.parent.is_dir()
|
| 233 |
+
):
|
| 234 |
raise SystemExit("output must be new and repetitions must equal five")
|
| 235 |
try:
|
| 236 |
pwd.getpwnam(args.user)
|
| 237 |
runner, model, _manifest = assets(args.assets_manifest)
|
| 238 |
values = [one(runner, model, args.user, index) for index in range(args.repetitions)]
|
| 239 |
+
args.output.write_text(
|
| 240 |
+
json.dumps({"repetitions": values, "result": "PASS"}, sort_keys=True) + "\n",
|
| 241 |
+
encoding="utf-8",
|
| 242 |
+
)
|
| 243 |
return 0
|
| 244 |
except (OSError, RuntimeError, TypeError, json.JSONDecodeError) as error:
|
| 245 |
if not args.output.exists():
|
| 246 |
+
args.output.write_text(
|
| 247 |
+
json.dumps({"error": str(error), "result": "FAIL"}, sort_keys=True) + "\n",
|
| 248 |
+
encoding="utf-8",
|
| 249 |
+
)
|
| 250 |
raise SystemExit(f"content AI smoke failed: {error}") from error
|
| 251 |
|
| 252 |
|
scripts/verify_release.py
CHANGED
|
@@ -13,16 +13,28 @@ from pathlib import Path
|
|
| 13 |
VERSION = "0.3.0"
|
| 14 |
PREFIX = f"lumi-eggcracker-{VERSION}/"
|
| 15 |
FORBIDDEN = (
|
| 16 |
-
"/mnt/" + "f/",
|
| 17 |
-
"
|
| 18 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
"skylark" + "-sentinel",
|
| 20 |
)
|
| 21 |
|
| 22 |
|
| 23 |
def text_from_zip(path: Path) -> str:
|
| 24 |
with zipfile.ZipFile(path) as archive:
|
| 25 |
-
return "\n".join(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
|
| 28 |
def digest_bytes(value: bytes) -> str:
|
|
@@ -35,26 +47,65 @@ def main() -> int:
|
|
| 35 |
parser.add_argument("--source-archive", required=True, type=Path)
|
| 36 |
parser.add_argument("--release-bundle", required=True, type=Path)
|
| 37 |
args = parser.parse_args()
|
| 38 |
-
if not all(
|
|
|
|
|
|
|
| 39 |
raise SystemExit("release artifacts are missing")
|
| 40 |
for path in (args.artifact, args.source_archive, args.release_bundle):
|
| 41 |
leaks = [item for item in FORBIDDEN if item in text_from_zip(path)]
|
| 42 |
if leaks:
|
| 43 |
raise SystemExit(f"forbidden public artifact content in {path.name}: {leaks}")
|
| 44 |
-
result = subprocess.run(
|
|
|
|
|
|
|
| 45 |
if result.returncode or result.stdout.strip() != VERSION:
|
| 46 |
raise SystemExit("artifact version is inconsistent")
|
| 47 |
-
manifest = json.loads(
|
|
|
|
|
|
|
| 48 |
if manifest.get("version") != VERSION or manifest.get("artifact") != args.artifact.name:
|
| 49 |
raise SystemExit("release manifest is inconsistent")
|
| 50 |
-
expected = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
with zipfile.ZipFile(args.release_bundle) as archive:
|
| 52 |
if set(archive.namelist()) != expected:
|
| 53 |
raise SystemExit("release bundle contents are inconsistent")
|
| 54 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
raise SystemExit("bundled artifact digest is inconsistent")
|
| 56 |
sums = (args.artifact.parent / "SHA256SUMS").read_text(encoding="utf-8")
|
| 57 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
raise SystemExit("checksums do not cover every release asset")
|
| 59 |
print(json.dumps({"result": "PASS", "version": VERSION}, sort_keys=True))
|
| 60 |
return 0
|
|
|
|
| 13 |
VERSION = "0.3.0"
|
| 14 |
PREFIX = f"lumi-eggcracker-{VERSION}/"
|
| 15 |
FORBIDDEN = (
|
| 16 |
+
"/mnt/" + "f/",
|
| 17 |
+
"f" + ":\\",
|
| 18 |
+
"network" + "-deny",
|
| 19 |
+
"network" + "_rule",
|
| 20 |
+
"nft" + "ables",
|
| 21 |
+
"/usr/sbin/" + "nft",
|
| 22 |
+
"b" + "20",
|
| 23 |
+
"brief" + " 1",
|
| 24 |
+
"brief" + "-",
|
| 25 |
+
"root" + "less",
|
| 26 |
+
"skylark" + " sentinel",
|
| 27 |
"skylark" + "-sentinel",
|
| 28 |
)
|
| 29 |
|
| 30 |
|
| 31 |
def text_from_zip(path: Path) -> str:
|
| 32 |
with zipfile.ZipFile(path) as archive:
|
| 33 |
+
return "\n".join(
|
| 34 |
+
archive.read(name).decode("utf-8", errors="ignore").lower()
|
| 35 |
+
for name in archive.namelist()
|
| 36 |
+
if name.endswith((".py", ".md", ".toml", ".txt"))
|
| 37 |
+
)
|
| 38 |
|
| 39 |
|
| 40 |
def digest_bytes(value: bytes) -> str:
|
|
|
|
| 47 |
parser.add_argument("--source-archive", required=True, type=Path)
|
| 48 |
parser.add_argument("--release-bundle", required=True, type=Path)
|
| 49 |
args = parser.parse_args()
|
| 50 |
+
if not all(
|
| 51 |
+
path.is_file() for path in (args.artifact, args.source_archive, args.release_bundle)
|
| 52 |
+
):
|
| 53 |
raise SystemExit("release artifacts are missing")
|
| 54 |
for path in (args.artifact, args.source_archive, args.release_bundle):
|
| 55 |
leaks = [item for item in FORBIDDEN if item in text_from_zip(path)]
|
| 56 |
if leaks:
|
| 57 |
raise SystemExit(f"forbidden public artifact content in {path.name}: {leaks}")
|
| 58 |
+
result = subprocess.run(
|
| 59 |
+
[sys.executable, str(args.artifact), "version"], capture_output=True, text=True, check=False
|
| 60 |
+
)
|
| 61 |
if result.returncode or result.stdout.strip() != VERSION:
|
| 62 |
raise SystemExit("artifact version is inconsistent")
|
| 63 |
+
manifest = json.loads(
|
| 64 |
+
(args.artifact.parent / "release-manifest.json").read_text(encoding="utf-8")
|
| 65 |
+
)
|
| 66 |
if manifest.get("version") != VERSION or manifest.get("artifact") != args.artifact.name:
|
| 67 |
raise SystemExit("release manifest is inconsistent")
|
| 68 |
+
expected = {
|
| 69 |
+
PREFIX + name
|
| 70 |
+
for name in (
|
| 71 |
+
args.artifact.name,
|
| 72 |
+
args.source_archive.name,
|
| 73 |
+
"release-manifest.json",
|
| 74 |
+
"SHA256SUMS",
|
| 75 |
+
"README.md",
|
| 76 |
+
"LICENSE",
|
| 77 |
+
"LIMITATIONS.md",
|
| 78 |
+
"SECURITY.md",
|
| 79 |
+
"SECURITY_MODEL.md",
|
| 80 |
+
"QUALIFICATION.md",
|
| 81 |
+
"RELEASE_NOTES.md",
|
| 82 |
+
"scripts/install.py",
|
| 83 |
+
"scripts/uninstall.py",
|
| 84 |
+
"scripts/verify_uninstalled.py",
|
| 85 |
+
"scripts/prepare_ai_smoke.py",
|
| 86 |
+
"scripts/ai_smoke_worker.py",
|
| 87 |
+
"scripts/smoke_local_ai.py",
|
| 88 |
+
"scripts/smoke_autonomous_ai.py",
|
| 89 |
+
"scripts/smoke_content_ai.py",
|
| 90 |
+
"scripts/run_content_matrix.py",
|
| 91 |
+
"scripts/run_autonomous_matrix.py",
|
| 92 |
+
)
|
| 93 |
+
}
|
| 94 |
with zipfile.ZipFile(args.release_bundle) as archive:
|
| 95 |
if set(archive.namelist()) != expected:
|
| 96 |
raise SystemExit("release bundle contents are inconsistent")
|
| 97 |
+
if (
|
| 98 |
+
digest_bytes(archive.read(PREFIX + args.artifact.name)) != manifest["sha256"]
|
| 99 |
+
or digest_bytes(archive.read(PREFIX + args.source_archive.name))
|
| 100 |
+
!= manifest["source_archive_sha256"]
|
| 101 |
+
):
|
| 102 |
raise SystemExit("bundled artifact digest is inconsistent")
|
| 103 |
sums = (args.artifact.parent / "SHA256SUMS").read_text(encoding="utf-8")
|
| 104 |
+
if (
|
| 105 |
+
args.artifact.name not in sums
|
| 106 |
+
or args.source_archive.name not in sums
|
| 107 |
+
or args.release_bundle.name not in sums
|
| 108 |
+
):
|
| 109 |
raise SystemExit("checksums do not cover every release asset")
|
| 110 |
print(json.dumps({"result": "PASS", "version": VERSION}, sort_keys=True))
|
| 111 |
return 0
|
src/lumi_eggcracker/artifacts.py
CHANGED
|
@@ -80,9 +80,20 @@ def validate_gguf_fd(descriptor: int) -> ArtifactEvidence:
|
|
| 80 |
raise JsonInputError("GGUF declared header exceeds the inspection budget")
|
| 81 |
header = _read_exact(descriptor, min(before.st_size, MAX_ARTIFACT_BYTES))
|
| 82 |
after = _regular(descriptor)
|
| 83 |
-
if (before.st_dev, before.st_ino, before.st_size) != (
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
raise JsonInputError("candidate model artifact changed during validation")
|
| 85 |
-
return ArtifactEvidence(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
|
| 88 |
def validate_path(path: Path) -> ArtifactEvidence | None:
|
|
@@ -100,7 +111,9 @@ def validate_path(path: Path) -> ArtifactEvidence | None:
|
|
| 100 |
os.close(descriptor)
|
| 101 |
|
| 102 |
|
| 103 |
-
def from_process_fds(
|
|
|
|
|
|
|
| 104 |
"""Inspect a bounded set of currently open target descriptors.
|
| 105 |
|
| 106 |
The descriptor is opened through ``/proc/<pid>/fd/<n>``. The link name is
|
|
|
|
| 80 |
raise JsonInputError("GGUF declared header exceeds the inspection budget")
|
| 81 |
header = _read_exact(descriptor, min(before.st_size, MAX_ARTIFACT_BYTES))
|
| 82 |
after = _regular(descriptor)
|
| 83 |
+
if (before.st_dev, before.st_ino, before.st_size) != (
|
| 84 |
+
after.st_dev,
|
| 85 |
+
after.st_ino,
|
| 86 |
+
after.st_size,
|
| 87 |
+
):
|
| 88 |
raise JsonInputError("candidate model artifact changed during validation")
|
| 89 |
+
return ArtifactEvidence(
|
| 90 |
+
f"gguf-v{version}",
|
| 91 |
+
"GGUF",
|
| 92 |
+
before.st_dev,
|
| 93 |
+
before.st_ino,
|
| 94 |
+
before.st_size,
|
| 95 |
+
hashlib.sha256(header).hexdigest(),
|
| 96 |
+
)
|
| 97 |
|
| 98 |
|
| 99 |
def validate_path(path: Path) -> ArtifactEvidence | None:
|
|
|
|
| 111 |
os.close(descriptor)
|
| 112 |
|
| 113 |
|
| 114 |
+
def from_process_fds(
|
| 115 |
+
snapshot: object, *, proc: Path = Path("/proc")
|
| 116 |
+
) -> tuple[ArtifactEvidence, ...]:
|
| 117 |
"""Inspect a bounded set of currently open target descriptors.
|
| 118 |
|
| 119 |
The descriptor is opened through ``/proc/<pid>/fd/<n>``. The link name is
|
src/lumi_eggcracker/detectors.py
CHANGED
|
@@ -46,7 +46,11 @@ class DetectionMatch:
|
|
| 46 |
|
| 47 |
|
| 48 |
def bundled_bytes() -> bytes:
|
| 49 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
|
| 52 |
def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
@@ -65,7 +69,11 @@ def _identifier(value: object) -> str:
|
|
| 65 |
|
| 66 |
|
| 67 |
def _values(value: object) -> tuple[str, ...]:
|
| 68 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
raise JsonInputError("detector evidence values are invalid")
|
| 70 |
if len(set(value)) != len(value):
|
| 71 |
raise JsonInputError("detector evidence values are duplicated")
|
|
@@ -74,13 +82,19 @@ def _values(value: object) -> tuple[str, ...]:
|
|
| 74 |
|
| 75 |
def load_catalogue(raw: bytes, *, expected_digest: str | None = None) -> Catalogue:
|
| 76 |
digest = hashlib.sha256(raw).hexdigest()
|
| 77 |
-
if expected_digest is not None and (
|
|
|
|
|
|
|
| 78 |
raise JsonInputError("detector catalogue digest is invalid")
|
| 79 |
try:
|
| 80 |
value = json.loads(raw.decode("utf-8"), object_pairs_hook=_pairs)
|
| 81 |
except (UnicodeDecodeError, json.JSONDecodeError, JsonInputError) as error:
|
| 82 |
raise JsonInputError(f"detector catalogue is invalid: {error}") from error
|
| 83 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
raise JsonInputError("detector catalogue schema is invalid")
|
| 85 |
raw_profiles = value["profiles"]
|
| 86 |
if not isinstance(raw_profiles, list) or not raw_profiles:
|
|
@@ -99,9 +113,15 @@ def load_catalogue(raw: bytes, *, expected_digest: str | None = None) -> Catalog
|
|
| 99 |
if not isinstance(item["all"], list) or not item["all"]:
|
| 100 |
raise JsonInputError("detector profile predicates are invalid")
|
| 101 |
for predicate in item["all"]:
|
| 102 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
raise JsonInputError("detector predicate schema is invalid")
|
| 104 |
-
predicates.append(
|
|
|
|
|
|
|
| 105 |
profile = Profile(identifier, path, tuple(predicates))
|
| 106 |
elif path == "CONTENT" and set(item) == {"id", "path", "require_all_groups"}:
|
| 107 |
raw_groups = item["require_all_groups"]
|
|
@@ -110,7 +130,12 @@ def load_catalogue(raw: bytes, *, expected_digest: str | None = None) -> Catalog
|
|
| 110 |
groups: list[dict[str, tuple[str, ...]]] = []
|
| 111 |
present: set[str] = set()
|
| 112 |
for group in raw_groups:
|
| 113 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
raise JsonInputError("content evidence group is invalid")
|
| 115 |
present.add(group["group"])
|
| 116 |
groups.append({"group": group["group"], "any": _values(group["any"])})
|
|
@@ -144,18 +169,26 @@ def _matches(snapshot: Snapshot, predicate: dict[str, Any]) -> bool:
|
|
| 144 |
raise JsonInputError("unknown detector predicate")
|
| 145 |
|
| 146 |
|
| 147 |
-
def match(
|
|
|
|
|
|
|
| 148 |
"""Return one complete profile match, never partial, fuzzy or scored evidence."""
|
| 149 |
supplied = evidence or {}
|
| 150 |
for profile in catalogue.profiles:
|
| 151 |
if profile.path == "FAST_NAME":
|
| 152 |
-
matched = tuple(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
if len(matched) == len(profile.predicates):
|
| 154 |
return DetectionMatch(profile.identifier, profile.path, matched)
|
| 155 |
else:
|
| 156 |
matched_ids: list[str] = []
|
| 157 |
for group in profile.groups:
|
| 158 |
-
values = tuple(
|
|
|
|
|
|
|
| 159 |
if not values:
|
| 160 |
break
|
| 161 |
matched_ids.extend(values)
|
|
@@ -171,7 +204,9 @@ def public_catalogue(catalogue: Catalogue) -> dict[str, Any]:
|
|
| 171 |
if profile.path == "FAST_NAME":
|
| 172 |
value["predicates"] = [item["kind"] for item in profile.predicates]
|
| 173 |
else:
|
| 174 |
-
value["evidence_groups"] = [
|
|
|
|
|
|
|
| 175 |
profiles.append(value)
|
| 176 |
return {"digest": catalogue.digest, "profiles": profiles, "schema_version": SCHEMA}
|
| 177 |
|
|
|
|
| 46 |
|
| 47 |
|
| 48 |
def bundled_bytes() -> bytes:
|
| 49 |
+
return (
|
| 50 |
+
importlib.resources.files("lumi_eggcracker")
|
| 51 |
+
.joinpath("detector_catalogue.json")
|
| 52 |
+
.read_bytes()
|
| 53 |
+
)
|
| 54 |
|
| 55 |
|
| 56 |
def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
|
|
| 69 |
|
| 70 |
|
| 71 |
def _values(value: object) -> tuple[str, ...]:
|
| 72 |
+
if (
|
| 73 |
+
not isinstance(value, list)
|
| 74 |
+
or not value
|
| 75 |
+
or not all(isinstance(item, str) and 1 <= len(item) <= 128 for item in value)
|
| 76 |
+
):
|
| 77 |
raise JsonInputError("detector evidence values are invalid")
|
| 78 |
if len(set(value)) != len(value):
|
| 79 |
raise JsonInputError("detector evidence values are duplicated")
|
|
|
|
| 82 |
|
| 83 |
def load_catalogue(raw: bytes, *, expected_digest: str | None = None) -> Catalogue:
|
| 84 |
digest = hashlib.sha256(raw).hexdigest()
|
| 85 |
+
if expected_digest is not None and (
|
| 86 |
+
not HEX.fullmatch(expected_digest) or digest != expected_digest
|
| 87 |
+
):
|
| 88 |
raise JsonInputError("detector catalogue digest is invalid")
|
| 89 |
try:
|
| 90 |
value = json.loads(raw.decode("utf-8"), object_pairs_hook=_pairs)
|
| 91 |
except (UnicodeDecodeError, json.JSONDecodeError, JsonInputError) as error:
|
| 92 |
raise JsonInputError(f"detector catalogue is invalid: {error}") from error
|
| 93 |
+
if (
|
| 94 |
+
not isinstance(value, dict)
|
| 95 |
+
or set(value) != {"profiles", "schema_version"}
|
| 96 |
+
or value.get("schema_version") != SCHEMA
|
| 97 |
+
):
|
| 98 |
raise JsonInputError("detector catalogue schema is invalid")
|
| 99 |
raw_profiles = value["profiles"]
|
| 100 |
if not isinstance(raw_profiles, list) or not raw_profiles:
|
|
|
|
| 113 |
if not isinstance(item["all"], list) or not item["all"]:
|
| 114 |
raise JsonInputError("detector profile predicates are invalid")
|
| 115 |
for predicate in item["all"]:
|
| 116 |
+
if (
|
| 117 |
+
not isinstance(predicate, dict)
|
| 118 |
+
or set(predicate) != {"kind", "values"}
|
| 119 |
+
or predicate["kind"] not in KINDS
|
| 120 |
+
):
|
| 121 |
raise JsonInputError("detector predicate schema is invalid")
|
| 122 |
+
predicates.append(
|
| 123 |
+
{"kind": predicate["kind"], "values": _values(predicate["values"])}
|
| 124 |
+
)
|
| 125 |
profile = Profile(identifier, path, tuple(predicates))
|
| 126 |
elif path == "CONTENT" and set(item) == {"id", "path", "require_all_groups"}:
|
| 127 |
raw_groups = item["require_all_groups"]
|
|
|
|
| 130 |
groups: list[dict[str, tuple[str, ...]]] = []
|
| 131 |
present: set[str] = set()
|
| 132 |
for group in raw_groups:
|
| 133 |
+
if (
|
| 134 |
+
not isinstance(group, dict)
|
| 135 |
+
or set(group) != {"any", "group"}
|
| 136 |
+
or group["group"] not in GROUPS
|
| 137 |
+
or group["group"] in present
|
| 138 |
+
):
|
| 139 |
raise JsonInputError("content evidence group is invalid")
|
| 140 |
present.add(group["group"])
|
| 141 |
groups.append({"group": group["group"], "any": _values(group["any"])})
|
|
|
|
| 169 |
raise JsonInputError("unknown detector predicate")
|
| 170 |
|
| 171 |
|
| 172 |
+
def match(
|
| 173 |
+
catalogue: Catalogue, snapshot: Snapshot, *, evidence: dict[str, set[str]] | None = None
|
| 174 |
+
) -> DetectionMatch | None:
|
| 175 |
"""Return one complete profile match, never partial, fuzzy or scored evidence."""
|
| 176 |
supplied = evidence or {}
|
| 177 |
for profile in catalogue.profiles:
|
| 178 |
if profile.path == "FAST_NAME":
|
| 179 |
+
matched = tuple(
|
| 180 |
+
predicate["kind"]
|
| 181 |
+
for predicate in profile.predicates
|
| 182 |
+
if _matches(snapshot, predicate)
|
| 183 |
+
)
|
| 184 |
if len(matched) == len(profile.predicates):
|
| 185 |
return DetectionMatch(profile.identifier, profile.path, matched)
|
| 186 |
else:
|
| 187 |
matched_ids: list[str] = []
|
| 188 |
for group in profile.groups:
|
| 189 |
+
values = tuple(
|
| 190 |
+
sorted(set(group["any"]).intersection(supplied.get(group["group"], set())))
|
| 191 |
+
)
|
| 192 |
if not values:
|
| 193 |
break
|
| 194 |
matched_ids.extend(values)
|
|
|
|
| 204 |
if profile.path == "FAST_NAME":
|
| 205 |
value["predicates"] = [item["kind"] for item in profile.predicates]
|
| 206 |
else:
|
| 207 |
+
value["evidence_groups"] = [
|
| 208 |
+
{"group": item["group"], "any": list(item["any"])} for item in profile.groups
|
| 209 |
+
]
|
| 210 |
profiles.append(value)
|
| 211 |
return {"digest": catalogue.digest, "profiles": profiles, "schema_version": SCHEMA}
|
| 212 |
|
src/lumi_eggcracker/discovery.py
CHANGED
|
@@ -38,7 +38,9 @@ class ProcessSnapshot:
|
|
| 38 |
|
| 39 |
|
| 40 |
def _read(path: Path, limit: int = MAX_READ) -> bytes:
|
| 41 |
-
descriptor = os.open(
|
|
|
|
|
|
|
| 42 |
try:
|
| 43 |
value = os.read(descriptor, limit + 1)
|
| 44 |
finally:
|
|
@@ -150,8 +152,12 @@ def snapshot(value: ProcessIdentity, *, proc: Path = PROC) -> ProcessSnapshot |
|
|
| 150 |
root = proc / str(value.pid)
|
| 151 |
try:
|
| 152 |
exe = os.readlink(root / "exe")
|
| 153 |
-
command = tuple(
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
uid = _uid(_read(root / "status", 8192).decode("utf-8"))
|
| 156 |
fd_entries = _fd_entries(root / "fd", limit=MAX_FDS)
|
| 157 |
fd_paths = tuple(item[1] for item in fd_entries)
|
|
@@ -160,10 +166,23 @@ def snapshot(value: ProcessIdentity, *, proc: Path = PROC) -> ProcessSnapshot |
|
|
| 160 |
if not command or not exe or len(exe) > 4096:
|
| 161 |
return None
|
| 162 |
maps = _map_paths(root / "maps")
|
| 163 |
-
return ProcessSnapshot(
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
result: list[ProcessSnapshot] = []
|
| 168 |
try:
|
| 169 |
candidates = sorted(int(item.name) for item in proc.iterdir() if item.name.isdigit())
|
|
|
|
| 38 |
|
| 39 |
|
| 40 |
def _read(path: Path, limit: int = MAX_READ) -> bytes:
|
| 41 |
+
descriptor = os.open(
|
| 42 |
+
path, os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
|
| 43 |
+
)
|
| 44 |
try:
|
| 45 |
value = os.read(descriptor, limit + 1)
|
| 46 |
finally:
|
|
|
|
| 152 |
root = proc / str(value.pid)
|
| 153 |
try:
|
| 154 |
exe = os.readlink(root / "exe")
|
| 155 |
+
command = tuple(
|
| 156 |
+
item for item in _read(root / "cmdline").decode("utf-8").split("\0") if item
|
| 157 |
+
)
|
| 158 |
+
cgroups = tuple(
|
| 159 |
+
line for line in _read(root / "cgroup", 8192).decode("utf-8").splitlines() if line
|
| 160 |
+
)
|
| 161 |
uid = _uid(_read(root / "status", 8192).decode("utf-8"))
|
| 162 |
fd_entries = _fd_entries(root / "fd", limit=MAX_FDS)
|
| 163 |
fd_paths = tuple(item[1] for item in fd_entries)
|
|
|
|
| 166 |
if not command or not exe or len(exe) > 4096:
|
| 167 |
return None
|
| 168 |
maps = _map_paths(root / "maps")
|
| 169 |
+
return ProcessSnapshot(
|
| 170 |
+
value,
|
| 171 |
+
uid,
|
| 172 |
+
exe,
|
| 173 |
+
Path(exe.removesuffix(" (deleted)")).name,
|
| 174 |
+
command,
|
| 175 |
+
cgroups,
|
| 176 |
+
fd_paths,
|
| 177 |
+
tuple(Path(item).name for item in maps),
|
| 178 |
+
fd_entries,
|
| 179 |
+
maps,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def scan(
|
| 184 |
+
*, proc: Path = PROC, exclude: Callable[[ProcessSnapshot], bool] | None = None
|
| 185 |
+
) -> list[ProcessSnapshot]:
|
| 186 |
result: list[ProcessSnapshot] = []
|
| 187 |
try:
|
| 188 |
candidates = sorted(int(item.name) for item in proc.iterdir() if item.name.isdigit())
|
src/lumi_eggcracker/elfmarkers.py
CHANGED
|
@@ -12,7 +12,14 @@ from .jsonio import JsonInputError
|
|
| 12 |
|
| 13 |
MAX_ELF_BYTES = 4 * 1024 * 1024
|
| 14 |
MAX_SECTIONS = 1024
|
| 15 |
-
LLAMA_MARKERS = frozenset(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
PINNED_LLAMA_BUILD_IDS = frozenset({"7c2bca7f8ea49e1c6e86adb14861e721e041f95e"})
|
| 17 |
|
| 18 |
|
|
@@ -41,21 +48,55 @@ def _symbols(descriptor: int, size: int) -> set[str]:
|
|
| 41 |
header = _read(descriptor, 0, 64)
|
| 42 |
if header[:4] != b"\x7fELF" or header[4:6] != b"\x02\x01":
|
| 43 |
raise JsonInputError("candidate runtime is not little-endian ELF64")
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
if header_size != 64 or not 1 <= section_count <= MAX_SECTIONS or section_size < 64:
|
| 46 |
raise JsonInputError("ELF section table is invalid")
|
| 47 |
-
if
|
|
|
|
|
|
|
|
|
|
| 48 |
raise JsonInputError("ELF section table exceeds inspection window")
|
| 49 |
-
sections = [
|
|
|
|
|
|
|
|
|
|
| 50 |
values: set[str] = set()
|
| 51 |
for entry in sections:
|
| 52 |
-
_name, kind, _flags, _address, offset, length, link, _info, _align, entry_size =
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
continue
|
| 55 |
if link >= section_count:
|
| 56 |
raise JsonInputError("ELF symbol table references invalid string table")
|
| 57 |
-
_n, string_kind, _f, _a, string_offset, string_length, _l, _i, _al, _es = struct.unpack(
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
raise JsonInputError("ELF string table is invalid")
|
| 60 |
strings = _read(descriptor, string_offset, string_length)
|
| 61 |
symbols = _read(descriptor, offset, length)
|
|
@@ -82,11 +123,17 @@ def _build_id(descriptor: int, size: int) -> str | None:
|
|
| 82 |
program_offset, entry_size, count = values[4], values[8], values[9]
|
| 83 |
if count == 0:
|
| 84 |
return None
|
| 85 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
raise JsonInputError("ELF program table is invalid")
|
| 87 |
for index in range(count):
|
| 88 |
entry = _read(descriptor, program_offset + index * entry_size, 56)
|
| 89 |
-
kind, _flags, offset, _virtual, _physical, length, _memory, _align = struct.unpack(
|
|
|
|
|
|
|
| 90 |
if kind != 4 or not length or offset + length > size or offset + length > MAX_ELF_BYTES:
|
| 91 |
continue
|
| 92 |
note = _read(descriptor, offset, length)
|
|
@@ -124,7 +171,11 @@ def inspect_path(path: Path) -> RuntimeEvidence | None:
|
|
| 124 |
# window. It may still qualify only through the exact build ID.
|
| 125 |
found = ()
|
| 126 |
after = os.fstat(descriptor)
|
| 127 |
-
if (before.st_dev, before.st_ino, before.st_size) != (
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
return None
|
| 129 |
if len(found) >= 2:
|
| 130 |
return RuntimeEvidence("llama-elf", "llama.cpp/GGML", "ELF_MARKERS", found)
|
|
|
|
| 12 |
|
| 13 |
MAX_ELF_BYTES = 4 * 1024 * 1024
|
| 14 |
MAX_SECTIONS = 1024
|
| 15 |
+
LLAMA_MARKERS = frozenset(
|
| 16 |
+
{
|
| 17 |
+
"llama_decode",
|
| 18 |
+
"llama_model_load_from_file",
|
| 19 |
+
"llama_model_load_from_splits",
|
| 20 |
+
"ggml_build_forward_expand",
|
| 21 |
+
}
|
| 22 |
+
)
|
| 23 |
PINNED_LLAMA_BUILD_IDS = frozenset({"7c2bca7f8ea49e1c6e86adb14861e721e041f95e"})
|
| 24 |
|
| 25 |
|
|
|
|
| 48 |
header = _read(descriptor, 0, 64)
|
| 49 |
if header[:4] != b"\x7fELF" or header[4:6] != b"\x02\x01":
|
| 50 |
raise JsonInputError("candidate runtime is not little-endian ELF64")
|
| 51 |
+
(
|
| 52 |
+
_type,
|
| 53 |
+
_machine,
|
| 54 |
+
_version,
|
| 55 |
+
_entry,
|
| 56 |
+
_phoff,
|
| 57 |
+
section_offset,
|
| 58 |
+
_flags,
|
| 59 |
+
header_size,
|
| 60 |
+
_phent,
|
| 61 |
+
_phnum,
|
| 62 |
+
section_size,
|
| 63 |
+
section_count,
|
| 64 |
+
_shstr,
|
| 65 |
+
) = struct.unpack("<HHIQQQIHHHHHH", header[16:])
|
| 66 |
if header_size != 64 or not 1 <= section_count <= MAX_SECTIONS or section_size < 64:
|
| 67 |
raise JsonInputError("ELF section table is invalid")
|
| 68 |
+
if (
|
| 69 |
+
section_offset + section_size * section_count > size
|
| 70 |
+
or section_offset + section_size * section_count > MAX_ELF_BYTES
|
| 71 |
+
):
|
| 72 |
raise JsonInputError("ELF section table exceeds inspection window")
|
| 73 |
+
sections = [
|
| 74 |
+
_read(descriptor, section_offset + index * section_size, 64)
|
| 75 |
+
for index in range(section_count)
|
| 76 |
+
]
|
| 77 |
values: set[str] = set()
|
| 78 |
for entry in sections:
|
| 79 |
+
_name, kind, _flags, _address, offset, length, link, _info, _align, entry_size = (
|
| 80 |
+
struct.unpack("<IIQQQQIIQQ", entry)
|
| 81 |
+
)
|
| 82 |
+
if (
|
| 83 |
+
kind not in {2, 11}
|
| 84 |
+
or entry_size != 24
|
| 85 |
+
or not length
|
| 86 |
+
or length > MAX_ELF_BYTES
|
| 87 |
+
or offset + length > size
|
| 88 |
+
):
|
| 89 |
continue
|
| 90 |
if link >= section_count:
|
| 91 |
raise JsonInputError("ELF symbol table references invalid string table")
|
| 92 |
+
_n, string_kind, _f, _a, string_offset, string_length, _l, _i, _al, _es = struct.unpack(
|
| 93 |
+
"<IIQQQQIIQQ", sections[link]
|
| 94 |
+
)
|
| 95 |
+
if (
|
| 96 |
+
string_kind != 3
|
| 97 |
+
or string_offset + string_length > size
|
| 98 |
+
or string_length > MAX_ELF_BYTES
|
| 99 |
+
):
|
| 100 |
raise JsonInputError("ELF string table is invalid")
|
| 101 |
strings = _read(descriptor, string_offset, string_length)
|
| 102 |
symbols = _read(descriptor, offset, length)
|
|
|
|
| 123 |
program_offset, entry_size, count = values[4], values[8], values[9]
|
| 124 |
if count == 0:
|
| 125 |
return None
|
| 126 |
+
if (
|
| 127 |
+
entry_size < 56
|
| 128 |
+
or not 1 <= count <= MAX_SECTIONS
|
| 129 |
+
or program_offset + entry_size * count > size
|
| 130 |
+
):
|
| 131 |
raise JsonInputError("ELF program table is invalid")
|
| 132 |
for index in range(count):
|
| 133 |
entry = _read(descriptor, program_offset + index * entry_size, 56)
|
| 134 |
+
kind, _flags, offset, _virtual, _physical, length, _memory, _align = struct.unpack(
|
| 135 |
+
"<IIQQQQQQ", entry
|
| 136 |
+
)
|
| 137 |
if kind != 4 or not length or offset + length > size or offset + length > MAX_ELF_BYTES:
|
| 138 |
continue
|
| 139 |
note = _read(descriptor, offset, length)
|
|
|
|
| 171 |
# window. It may still qualify only through the exact build ID.
|
| 172 |
found = ()
|
| 173 |
after = os.fstat(descriptor)
|
| 174 |
+
if (before.st_dev, before.st_ino, before.st_size) != (
|
| 175 |
+
after.st_dev,
|
| 176 |
+
after.st_ino,
|
| 177 |
+
after.st_size,
|
| 178 |
+
):
|
| 179 |
return None
|
| 180 |
if len(found) >= 2:
|
| 181 |
return RuntimeEvidence("llama-elf", "llama.cpp/GGML", "ELF_MARKERS", found)
|
src/lumi_eggcracker/observation.py
CHANGED
|
@@ -21,11 +21,17 @@ class ObservationStore:
|
|
| 21 |
def __init__(self) -> None:
|
| 22 |
self._values: dict[Hashable, Observation] = {}
|
| 23 |
|
| 24 |
-
def observe(
|
|
|
|
|
|
|
| 25 |
now = time.monotonic_ns() if now_ns is None else now_ns
|
| 26 |
self.expire(now_ns=now)
|
| 27 |
previous = self._values.get(identity)
|
| 28 |
-
value = Observation(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
self._values[identity] = value
|
| 30 |
if len(self._values) > MAX_OBSERVATIONS:
|
| 31 |
oldest = min(self._values, key=lambda key: self._values[key].last_seen_ns)
|
|
|
|
| 21 |
def __init__(self) -> None:
|
| 22 |
self._values: dict[Hashable, Observation] = {}
|
| 23 |
|
| 24 |
+
def observe(
|
| 25 |
+
self, identity: Hashable, evidence: set[str], *, now_ns: int | None = None
|
| 26 |
+
) -> Observation:
|
| 27 |
now = time.monotonic_ns() if now_ns is None else now_ns
|
| 28 |
self.expire(now_ns=now)
|
| 29 |
previous = self._values.get(identity)
|
| 30 |
+
value = Observation(
|
| 31 |
+
frozenset(evidence) | (previous.evidence if previous else frozenset()),
|
| 32 |
+
previous.first_seen_ns if previous else now,
|
| 33 |
+
now,
|
| 34 |
+
)
|
| 35 |
self._values[identity] = value
|
| 36 |
if len(self._values) > MAX_OBSERVATIONS:
|
| 37 |
oldest = min(self._values, key=lambda key: self._values[key].last_seen_ns)
|
src/lumi_eggcracker/supervisor.py
CHANGED
|
@@ -110,7 +110,20 @@ class Supervisor:
|
|
| 110 |
if os.geteuid() != 0:
|
| 111 |
raise JsonInputError("supervisor must run as root")
|
| 112 |
policy = load_regular_json(policy_path)
|
| 113 |
-
expected = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
if set(policy) != expected or policy["schema_version"] != POLICY_SCHEMA:
|
| 115 |
raise JsonInputError("supervisor policy schema is invalid")
|
| 116 |
for key in ("operator_gid", "operator_uid", "workload_gid", "workload_uid"):
|
|
@@ -118,14 +131,24 @@ class Supervisor:
|
|
| 118 |
raise JsonInputError("supervisor policy identity is invalid")
|
| 119 |
if policy["operator_uid"] == policy["workload_uid"] or policy["workload_uid"] == 0:
|
| 120 |
raise JsonInputError("operator and workload identities must be distinct non-root users")
|
| 121 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
raise JsonInputError("supervisor policy path is invalid")
|
| 123 |
if policy["version"] != __version__ or not isinstance(policy["source_commit"], str):
|
| 124 |
raise JsonInputError("supervisor build identity is invalid")
|
| 125 |
catalogue_path = Path(policy["catalogue_path"])
|
| 126 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
raise JsonInputError("supervisor detector catalogue path is invalid")
|
| 128 |
-
self.catalogue: Catalogue = load_catalogue(
|
|
|
|
|
|
|
| 129 |
self.policy = policy
|
| 130 |
self.runs = STATE_DIR / "runs"
|
| 131 |
self.names = STATE_DIR / "names"
|
|
@@ -155,10 +178,24 @@ class Supervisor:
|
|
| 155 |
def _show(self, unit: str) -> dict[str, str]:
|
| 156 |
if not unit.startswith(UNIT_PREFIX) or not unit.endswith(".service"):
|
| 157 |
raise JsonInputError("unit is outside Eggcracker namespace")
|
| 158 |
-
result = self._run(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
if result.returncode:
|
| 160 |
return {"ActiveState": "unknown", "ControlGroup": "", "TasksMax": ""}
|
| 161 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
def _new_lock(self, name: str) -> threading.Lock:
|
| 164 |
with self.lock_guard:
|
|
@@ -222,7 +259,16 @@ class Supervisor:
|
|
| 222 |
# Workloads need traversal only to their group-readable gate. The
|
| 223 |
# control socket remains a root/operator 0660 inode, so traversal does
|
| 224 |
# not grant control-socket access or directory listing.
|
| 225 |
-
for path, mode, gid in (
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
path.mkdir(mode=mode, parents=True, exist_ok=True)
|
| 227 |
os.chown(path, 0, gid)
|
| 228 |
os.chmod(path, mode)
|
|
@@ -248,7 +294,9 @@ class Supervisor:
|
|
| 248 |
if root.is_symlink():
|
| 249 |
raise JsonInputError("quarantine root is a symlink")
|
| 250 |
root.mkdir(mode=0o700, exist_ok=True)
|
| 251 |
-
if not root.is_dir() or not all(
|
|
|
|
|
|
|
| 252 |
raise JsonInputError("delegated quarantine cgroup is unavailable")
|
| 253 |
return root
|
| 254 |
|
|
@@ -258,7 +306,9 @@ class Supervisor:
|
|
| 258 |
record = load_run(self.runs, path.stem)
|
| 259 |
except JsonInputError:
|
| 260 |
continue
|
| 261 |
-
if record["state"] in ACTIVE_STATES and any(
|
|
|
|
|
|
|
| 262 |
return True
|
| 263 |
return False
|
| 264 |
|
|
@@ -279,37 +329,141 @@ class Supervisor:
|
|
| 279 |
|
| 280 |
def _store_detection(self, value: dict[str, Any]) -> None:
|
| 281 |
write_atomic(self._detection_path(value["event_id"]), value)
|
| 282 |
-
records = sorted(
|
|
|
|
|
|
|
| 283 |
for path in records[DETECTION_LIMIT:]:
|
| 284 |
path.unlink(missing_ok=True)
|
| 285 |
|
| 286 |
-
def _detection_receipt(
|
| 287 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
if detected.path == "CONTENT":
|
| 289 |
detector["model"] = content[0].public() if content else {}
|
| 290 |
detector["runtime"] = runtimes[0].public() if runtimes else {}
|
| 291 |
-
detector["observation"] = {
|
| 292 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
if result is None:
|
| 294 |
value["result"] = "CONTAINMENT_FAILED"
|
| 295 |
value["error"] = (error or "containment failed")[:160]
|
| 296 |
return value
|
| 297 |
-
value.update(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
return value
|
| 299 |
|
| 300 |
-
def _enforce_discovery(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
try:
|
| 302 |
if self.quarantine_root is None:
|
| 303 |
raise JsonInputError("quarantine root is unavailable")
|
| 304 |
self.operations.append("pidfd.stop")
|
| 305 |
result = contain(snapshot.identity, self.quarantine_root, event_id)
|
| 306 |
self.operations.append("cgroup.kill")
|
| 307 |
-
receipt = self._detection_receipt(
|
| 308 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
self._store_detection(receipt)
|
| 310 |
except (JsonInputError, OSError, RuntimeError, ProcessLookupError) as error:
|
| 311 |
-
receipt = self._detection_receipt(
|
| 312 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
try:
|
| 314 |
self._store_detection(receipt)
|
| 315 |
except (JsonInputError, OSError):
|
|
@@ -323,7 +477,9 @@ class Supervisor:
|
|
| 323 |
approvals = load_approvals(self.approvals)
|
| 324 |
except JsonInputError:
|
| 325 |
approvals = [] # A corrupt approval never authorizes a matching workload.
|
| 326 |
-
for snapshot in scan(
|
|
|
|
|
|
|
| 327 |
detected = match(self.catalogue, snapshot)
|
| 328 |
content: tuple[ArtifactEvidence, ...] = ()
|
| 329 |
runtimes: tuple[RuntimeEvidence, ...] = ()
|
|
@@ -331,14 +487,20 @@ class Supervisor:
|
|
| 331 |
if detected is None:
|
| 332 |
content = artifacts_from_snapshot(snapshot)
|
| 333 |
runtimes = runtime_from_snapshot(snapshot)
|
| 334 |
-
supplied = {
|
| 335 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
first_seen_ns = observation.first_seen_ns
|
| 337 |
# Both groups must be valid in this snapshot. Observations only
|
| 338 |
# provide bounded timing, never stale evidence joining.
|
| 339 |
detected = match(self.catalogue, snapshot, evidence=supplied)
|
| 340 |
if detected is None:
|
| 341 |
continue
|
|
|
|
| 342 |
try:
|
| 343 |
executable_sha256 = self._cached_executable_digest(snapshot)
|
| 344 |
except (JsonInputError, OSError):
|
|
@@ -351,9 +513,31 @@ class Supervisor:
|
|
| 351 |
self.discovery_active.add(snapshot.identity)
|
| 352 |
event_id = os.urandom(12).hex()
|
| 353 |
if synchronous:
|
| 354 |
-
self._enforce_discovery(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
else:
|
| 356 |
-
threading.Thread(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
|
| 358 |
def _discovery_loop(self) -> None:
|
| 359 |
while not self.stop_event.is_set():
|
|
@@ -365,14 +549,20 @@ class Supervisor:
|
|
| 365 |
|
| 366 |
def _cleanup(self, unit: str) -> dict[str, Any]:
|
| 367 |
result = self._run(["/usr/bin/systemctl", "stop", unit])
|
| 368 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
|
| 370 |
def _write_receipt(self, receipt: dict[str, Any], event_id: str) -> None:
|
| 371 |
receipt["receipt_written_utc"] = dt.datetime.now(dt.UTC).isoformat().replace("+00:00", "Z")
|
| 372 |
self.operations.append("durable-receipt")
|
| 373 |
write_atomic(self._receipt_path(event_id), receipt)
|
| 374 |
|
| 375 |
-
def _contain(
|
|
|
|
|
|
|
| 376 |
"""Direct cgroup.kill is the first trigger-side effect; cleanup is post-proof only."""
|
| 377 |
lock = self._new_lock(record["run_id"])
|
| 378 |
with lock:
|
|
@@ -392,7 +582,18 @@ class Supervisor:
|
|
| 392 |
self._store(record)
|
| 393 |
raise JsonInputError(f"containment failed: {error}") from error
|
| 394 |
event_id = os.urandom(12).hex()
|
| 395 |
-
receipt = make_receipt(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
try:
|
| 397 |
self._write_receipt(receipt, event_id)
|
| 398 |
record["state"] = "TERMINATED"
|
|
@@ -400,7 +601,9 @@ class Supervisor:
|
|
| 400 |
except Exception as error:
|
| 401 |
record["state"] = "CONTAINED_RECEIPT_FAILED"
|
| 402 |
self._store(record)
|
| 403 |
-
raise JsonInputError(
|
|
|
|
|
|
|
| 404 |
# Cleanup is deliberately not in the enforcement or proof path.
|
| 405 |
cleanup = self._cleanup(record["unit"])
|
| 406 |
receipt["cleanup"] = cleanup
|
|
@@ -519,11 +722,36 @@ class Supervisor:
|
|
| 519 |
raise JsonInputError("max_pids must be from 4 to 4096")
|
| 520 |
with self.start_lock:
|
| 521 |
if name_path(self.names, name).exists() or self._active_exists():
|
| 522 |
-
raise JsonInputError(
|
|
|
|
|
|
|
| 523 |
run_id = os.urandom(12).hex()
|
| 524 |
unit = f"{UNIT_PREFIX}{run_id}.service"
|
| 525 |
gate = self._make_gate(run_id)
|
| 526 |
-
result = self._run(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 527 |
if result.returncode:
|
| 528 |
gate.unlink(missing_ok=True)
|
| 529 |
raise JsonInputError(result.stderr.strip() or "system workload launch failed")
|
|
@@ -538,7 +766,23 @@ class Supervisor:
|
|
| 538 |
if props.get("ActiveState") != "active" or not props.get("ControlGroup"):
|
| 539 |
raise JsonInputError("gated workload did not become active")
|
| 540 |
identity = capture_identity(props["ControlGroup"], run_id, unit)
|
| 541 |
-
record = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 542 |
self._store(record)
|
| 543 |
ready = threading.Event()
|
| 544 |
watcher = threading.Thread(target=self._watch, args=(record, ready), daemon=True)
|
|
@@ -551,7 +795,13 @@ class Supervisor:
|
|
| 551 |
if record["state"] in ACTIVE_STATES:
|
| 552 |
record["state"] = "RUNNING"
|
| 553 |
self._store(record)
|
| 554 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 555 |
except Exception:
|
| 556 |
gate.unlink(missing_ok=True)
|
| 557 |
try:
|
|
@@ -569,7 +819,25 @@ class Supervisor:
|
|
| 569 |
if not RUN_ID.fullmatch(run_id):
|
| 570 |
raise JsonInputError("orphan cgroup identity is invalid")
|
| 571 |
identity = capture_identity(cgroup, run_id, unit)
|
| 572 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 573 |
|
| 574 |
def _recover(self) -> None:
|
| 575 |
recorded_ids: set[str] = set()
|
|
@@ -589,16 +857,36 @@ class Supervisor:
|
|
| 589 |
continue
|
| 590 |
run_id = path.name.removeprefix(UNIT_PREFIX).removesuffix(".service")
|
| 591 |
if RUN_ID.fullmatch(run_id) and run_id not in recorded_ids:
|
| 592 |
-
self._contain(
|
|
|
|
|
|
|
|
|
|
| 593 |
|
| 594 |
def handle(self, value: dict[str, Any]) -> dict[str, Any]:
|
| 595 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 596 |
raise JsonInputError("request contract is invalid")
|
| 597 |
action, args = value["action"], value["args"]
|
| 598 |
if action == "doctor" and not args:
|
| 599 |
-
available =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 600 |
ready = available and pidfd_available() and self.quarantine_root is not None
|
| 601 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 602 |
if action == "start":
|
| 603 |
return self._start(args)
|
| 604 |
if action == "status" and set(args) == {"name"}:
|
|
@@ -606,23 +894,45 @@ class Supervisor:
|
|
| 606 |
record = self._load(args["name"])
|
| 607 |
except JsonInputError:
|
| 608 |
record = self._latest_by_name(args["name"])
|
| 609 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 610 |
if action == "list" and not args:
|
| 611 |
-
runs = [
|
|
|
|
|
|
|
|
|
|
| 612 |
return {"runs": runs}
|
| 613 |
if action == "approve" and set(args) == {"argv", "name", "uid"}:
|
| 614 |
-
value = create_approval(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 615 |
return {"approval": public_approval(value), "result": "APPROVED"}
|
| 616 |
if action == "revoke" and set(args) == {"name"}:
|
| 617 |
return revoke(self.approvals, args["name"])
|
| 618 |
if action == "approvals" and not args:
|
| 619 |
-
return {
|
|
|
|
|
|
|
| 620 |
if action == "detections" and not args:
|
| 621 |
values: list[dict[str, Any]] = []
|
| 622 |
for path in sorted(self.detections.glob("*.json"), reverse=True):
|
| 623 |
try:
|
| 624 |
value = load_regular_json(path)
|
| 625 |
-
values.append(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 626 |
except (JsonInputError, KeyError):
|
| 627 |
continue
|
| 628 |
return {"detections": values[:100]}
|
|
@@ -648,7 +958,9 @@ class Supervisor:
|
|
| 648 |
with connection:
|
| 649 |
connection.settimeout(3.0)
|
| 650 |
try:
|
| 651 |
-
_pid, uid, _gid = struct.unpack(
|
|
|
|
|
|
|
| 652 |
if uid not in {0, self.operator_uid}:
|
| 653 |
raise JsonInputError("peer uid is not authorized")
|
| 654 |
_send(connection, {"ok": True, "value": self.handle(_receive(connection))})
|
|
@@ -665,6 +977,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
| 665 |
parser.add_argument("--policy", required=True, type=Path)
|
| 666 |
args = parser.parse_args(argv)
|
| 667 |
supervisor = Supervisor(args.policy)
|
|
|
|
| 668 |
def stop(*_: object) -> None:
|
| 669 |
supervisor.stop_event.set()
|
| 670 |
raise SystemExit(0)
|
|
|
|
| 110 |
if os.geteuid() != 0:
|
| 111 |
raise JsonInputError("supervisor must run as root")
|
| 112 |
policy = load_regular_json(policy_path)
|
| 113 |
+
expected = {
|
| 114 |
+
"catalogue_path",
|
| 115 |
+
"catalogue_sha256",
|
| 116 |
+
"operator_gid",
|
| 117 |
+
"operator_uid",
|
| 118 |
+
"schema_version",
|
| 119 |
+
"socket_path",
|
| 120 |
+
"source_commit",
|
| 121 |
+
"state_dir",
|
| 122 |
+
"unit_prefix",
|
| 123 |
+
"version",
|
| 124 |
+
"workload_gid",
|
| 125 |
+
"workload_uid",
|
| 126 |
+
}
|
| 127 |
if set(policy) != expected or policy["schema_version"] != POLICY_SCHEMA:
|
| 128 |
raise JsonInputError("supervisor policy schema is invalid")
|
| 129 |
for key in ("operator_gid", "operator_uid", "workload_gid", "workload_uid"):
|
|
|
|
| 131 |
raise JsonInputError("supervisor policy identity is invalid")
|
| 132 |
if policy["operator_uid"] == policy["workload_uid"] or policy["workload_uid"] == 0:
|
| 133 |
raise JsonInputError("operator and workload identities must be distinct non-root users")
|
| 134 |
+
if (
|
| 135 |
+
Path(policy["socket_path"]) != SOCKET_PATH
|
| 136 |
+
or Path(policy["state_dir"]) != STATE_DIR
|
| 137 |
+
or policy["unit_prefix"] != UNIT_PREFIX
|
| 138 |
+
):
|
| 139 |
raise JsonInputError("supervisor policy path is invalid")
|
| 140 |
if policy["version"] != __version__ or not isinstance(policy["source_commit"], str):
|
| 141 |
raise JsonInputError("supervisor build identity is invalid")
|
| 142 |
catalogue_path = Path(policy["catalogue_path"])
|
| 143 |
+
if (
|
| 144 |
+
catalogue_path != Path("/etc/lumi-eggcracker/detector_catalogue.json")
|
| 145 |
+
or catalogue_path.is_symlink()
|
| 146 |
+
or not catalogue_path.is_file()
|
| 147 |
+
):
|
| 148 |
raise JsonInputError("supervisor detector catalogue path is invalid")
|
| 149 |
+
self.catalogue: Catalogue = load_catalogue(
|
| 150 |
+
catalogue_path.read_bytes(), expected_digest=policy["catalogue_sha256"]
|
| 151 |
+
)
|
| 152 |
self.policy = policy
|
| 153 |
self.runs = STATE_DIR / "runs"
|
| 154 |
self.names = STATE_DIR / "names"
|
|
|
|
| 178 |
def _show(self, unit: str) -> dict[str, str]:
|
| 179 |
if not unit.startswith(UNIT_PREFIX) or not unit.endswith(".service"):
|
| 180 |
raise JsonInputError("unit is outside Eggcracker namespace")
|
| 181 |
+
result = self._run(
|
| 182 |
+
[
|
| 183 |
+
"/usr/bin/systemctl",
|
| 184 |
+
"show",
|
| 185 |
+
unit,
|
| 186 |
+
"--property=ActiveState",
|
| 187 |
+
"--property=ControlGroup",
|
| 188 |
+
"--property=TasksMax",
|
| 189 |
+
]
|
| 190 |
+
)
|
| 191 |
if result.returncode:
|
| 192 |
return {"ActiveState": "unknown", "ControlGroup": "", "TasksMax": ""}
|
| 193 |
+
return {
|
| 194 |
+
key: value
|
| 195 |
+
for key, value in (
|
| 196 |
+
line.split("=", 1) for line in result.stdout.splitlines() if "=" in line
|
| 197 |
+
)
|
| 198 |
+
}
|
| 199 |
|
| 200 |
def _new_lock(self, name: str) -> threading.Lock:
|
| 201 |
with self.lock_guard:
|
|
|
|
| 259 |
# Workloads need traversal only to their group-readable gate. The
|
| 260 |
# control socket remains a root/operator 0660 inode, so traversal does
|
| 261 |
# not grant control-socket access or directory listing.
|
| 262 |
+
for path, mode, gid in (
|
| 263 |
+
(SOCKET_PATH.parent, 0o711, self.policy["operator_gid"]),
|
| 264 |
+
(GATES_DIR, 0o710, self.policy["workload_gid"]),
|
| 265 |
+
(STATE_DIR, 0o700, 0),
|
| 266 |
+
(self.runs, 0o700, 0),
|
| 267 |
+
(self.names, 0o700, 0),
|
| 268 |
+
(self.receipts, 0o700, 0),
|
| 269 |
+
(self.approvals, 0o700, 0),
|
| 270 |
+
(self.detections, 0o700, 0),
|
| 271 |
+
):
|
| 272 |
path.mkdir(mode=mode, parents=True, exist_ok=True)
|
| 273 |
os.chown(path, 0, gid)
|
| 274 |
os.chmod(path, mode)
|
|
|
|
| 294 |
if root.is_symlink():
|
| 295 |
raise JsonInputError("quarantine root is a symlink")
|
| 296 |
root.mkdir(mode=0o700, exist_ok=True)
|
| 297 |
+
if not root.is_dir() or not all(
|
| 298 |
+
(root / name).is_file() for name in ("cgroup.events", "cgroup.procs")
|
| 299 |
+
):
|
| 300 |
raise JsonInputError("delegated quarantine cgroup is unavailable")
|
| 301 |
return root
|
| 302 |
|
|
|
|
| 306 |
record = load_run(self.runs, path.stem)
|
| 307 |
except JsonInputError:
|
| 308 |
continue
|
| 309 |
+
if record["state"] in ACTIVE_STATES and any(
|
| 310 |
+
line.endswith(":" + record["cgroup"]) for line in snapshot.cgroups
|
| 311 |
+
):
|
| 312 |
return True
|
| 313 |
return False
|
| 314 |
|
|
|
|
| 329 |
|
| 330 |
def _store_detection(self, value: dict[str, Any]) -> None:
|
| 331 |
write_atomic(self._detection_path(value["event_id"]), value)
|
| 332 |
+
records = sorted(
|
| 333 |
+
self.detections.glob("*.json"), key=lambda item: item.stat().st_mtime_ns, reverse=True
|
| 334 |
+
)
|
| 335 |
for path in records[DETECTION_LIMIT:]:
|
| 336 |
path.unlink(missing_ok=True)
|
| 337 |
|
| 338 |
+
def _detection_receipt(
|
| 339 |
+
self,
|
| 340 |
+
*,
|
| 341 |
+
event_id: str,
|
| 342 |
+
snapshot: ProcessSnapshot,
|
| 343 |
+
detected: DetectionMatch,
|
| 344 |
+
content: tuple[ArtifactEvidence, ...],
|
| 345 |
+
runtimes: tuple[RuntimeEvidence, ...],
|
| 346 |
+
first_seen_ns: int,
|
| 347 |
+
qualified_ns: int,
|
| 348 |
+
executable_sha256: str,
|
| 349 |
+
result: AdoptionResult | None,
|
| 350 |
+
error: str | None,
|
| 351 |
+
) -> dict[str, Any]:
|
| 352 |
+
detector: dict[str, Any] = {
|
| 353 |
+
"catalogue_schema": "lumi-eggcracker.detectors.v2",
|
| 354 |
+
"detection_path": detected.path,
|
| 355 |
+
"matched_evidence": list(detected.evidence),
|
| 356 |
+
"matched_predicates": list(detected.evidence),
|
| 357 |
+
"profile": detected.profile,
|
| 358 |
+
}
|
| 359 |
if detected.path == "CONTENT":
|
| 360 |
detector["model"] = content[0].public() if content else {}
|
| 361 |
detector["runtime"] = runtimes[0].public() if runtimes else {}
|
| 362 |
+
detector["observation"] = {
|
| 363 |
+
"first_seen_monotonic_ns": first_seen_ns,
|
| 364 |
+
"qualified_monotonic_ns": qualified_ns,
|
| 365 |
+
}
|
| 366 |
+
value: dict[str, Any] = {
|
| 367 |
+
"catalogue_sha256": self.catalogue.digest,
|
| 368 |
+
"detector": detector,
|
| 369 |
+
"event_id": event_id,
|
| 370 |
+
"executable": {"basename": snapshot.exe_basename, "sha256": executable_sha256},
|
| 371 |
+
"observed": {
|
| 372 |
+
"argv_count": len(snapshot.argv),
|
| 373 |
+
"argv_sha256": hashlib.sha256("\0".join(snapshot.argv).encode("utf-8")).hexdigest(),
|
| 374 |
+
"pid": snapshot.identity.pid,
|
| 375 |
+
"start_time": snapshot.identity.start_time,
|
| 376 |
+
"uid": snapshot.uid,
|
| 377 |
+
},
|
| 378 |
+
"receipt_written_utc": None,
|
| 379 |
+
"schema_version": "lumi-eggcracker.detection-receipt.v2",
|
| 380 |
+
"source_commit": self.policy["source_commit"],
|
| 381 |
+
"trigger": {"kind": "UNAPPROVED_AI_MATCH"},
|
| 382 |
+
"version": __version__,
|
| 383 |
+
}
|
| 384 |
if result is None:
|
| 385 |
value["result"] = "CONTAINMENT_FAILED"
|
| 386 |
value["error"] = (error or "containment failed")[:160]
|
| 387 |
return value
|
| 388 |
+
value.update(
|
| 389 |
+
{
|
| 390 |
+
"result": "TERMINATED",
|
| 391 |
+
"capture": {
|
| 392 |
+
"captured_processes": len(result.captured),
|
| 393 |
+
"fixed_point_scans": result.fixed_point_scans,
|
| 394 |
+
"quarantine_cgroup": str(result.identity.path),
|
| 395 |
+
"quarantine_device": result.identity.device,
|
| 396 |
+
"quarantine_inode": result.identity.inode,
|
| 397 |
+
},
|
| 398 |
+
"containment": {
|
| 399 |
+
"empty_verified_monotonic_ns": result.empty_ns,
|
| 400 |
+
"first_stop_monotonic_ns": result.first_stop_ns,
|
| 401 |
+
"kill_write_completed_monotonic_ns": result.kill_complete_ns,
|
| 402 |
+
"kill_write_started_monotonic_ns": result.kill_started_ns,
|
| 403 |
+
"primitive": "pidfd-stop+cgroup.kill",
|
| 404 |
+
"qualification_to_first_stop_ms": (result.first_stop_ns - qualified_ns)
|
| 405 |
+
/ 1_000_000,
|
| 406 |
+
"root_populated": result.proof.root_populated,
|
| 407 |
+
"surviving_pids": result.proof.surviving_pids,
|
| 408 |
+
"trigger_to_empty_ms": (result.empty_ns - result.first_stop_ns) / 1_000_000,
|
| 409 |
+
},
|
| 410 |
+
"trigger": {
|
| 411 |
+
"kind": "UNAPPROVED_AI_MATCH",
|
| 412 |
+
"observed_monotonic_ns": result.first_stop_ns,
|
| 413 |
+
},
|
| 414 |
+
}
|
| 415 |
+
)
|
| 416 |
return value
|
| 417 |
|
| 418 |
+
def _enforce_discovery(
|
| 419 |
+
self,
|
| 420 |
+
snapshot: ProcessSnapshot,
|
| 421 |
+
detected: DetectionMatch,
|
| 422 |
+
content: tuple[ArtifactEvidence, ...],
|
| 423 |
+
runtimes: tuple[RuntimeEvidence, ...],
|
| 424 |
+
first_seen_ns: int,
|
| 425 |
+
qualified_ns: int,
|
| 426 |
+
executable_sha256: str,
|
| 427 |
+
event_id: str,
|
| 428 |
+
) -> None:
|
| 429 |
try:
|
| 430 |
if self.quarantine_root is None:
|
| 431 |
raise JsonInputError("quarantine root is unavailable")
|
| 432 |
self.operations.append("pidfd.stop")
|
| 433 |
result = contain(snapshot.identity, self.quarantine_root, event_id)
|
| 434 |
self.operations.append("cgroup.kill")
|
| 435 |
+
receipt = self._detection_receipt(
|
| 436 |
+
event_id=event_id,
|
| 437 |
+
snapshot=snapshot,
|
| 438 |
+
detected=detected,
|
| 439 |
+
content=content,
|
| 440 |
+
runtimes=runtimes,
|
| 441 |
+
first_seen_ns=first_seen_ns,
|
| 442 |
+
qualified_ns=qualified_ns,
|
| 443 |
+
executable_sha256=executable_sha256,
|
| 444 |
+
result=result,
|
| 445 |
+
error=None,
|
| 446 |
+
)
|
| 447 |
+
receipt["receipt_written_utc"] = (
|
| 448 |
+
dt.datetime.now(dt.UTC).isoformat().replace("+00:00", "Z")
|
| 449 |
+
)
|
| 450 |
self._store_detection(receipt)
|
| 451 |
except (JsonInputError, OSError, RuntimeError, ProcessLookupError) as error:
|
| 452 |
+
receipt = self._detection_receipt(
|
| 453 |
+
event_id=event_id,
|
| 454 |
+
snapshot=snapshot,
|
| 455 |
+
detected=detected,
|
| 456 |
+
content=content,
|
| 457 |
+
runtimes=runtimes,
|
| 458 |
+
first_seen_ns=first_seen_ns,
|
| 459 |
+
qualified_ns=qualified_ns,
|
| 460 |
+
executable_sha256=executable_sha256,
|
| 461 |
+
result=None,
|
| 462 |
+
error=str(error),
|
| 463 |
+
)
|
| 464 |
+
receipt["receipt_written_utc"] = (
|
| 465 |
+
dt.datetime.now(dt.UTC).isoformat().replace("+00:00", "Z")
|
| 466 |
+
)
|
| 467 |
try:
|
| 468 |
self._store_detection(receipt)
|
| 469 |
except (JsonInputError, OSError):
|
|
|
|
| 477 |
approvals = load_approvals(self.approvals)
|
| 478 |
except JsonInputError:
|
| 479 |
approvals = [] # A corrupt approval never authorizes a matching workload.
|
| 480 |
+
for snapshot in scan(
|
| 481 |
+
exclude=lambda item: item.identity.pid == os.getpid() or self._managed(item)
|
| 482 |
+
):
|
| 483 |
detected = match(self.catalogue, snapshot)
|
| 484 |
content: tuple[ArtifactEvidence, ...] = ()
|
| 485 |
runtimes: tuple[RuntimeEvidence, ...] = ()
|
|
|
|
| 487 |
if detected is None:
|
| 488 |
content = artifacts_from_snapshot(snapshot)
|
| 489 |
runtimes = runtime_from_snapshot(snapshot)
|
| 490 |
+
supplied = {
|
| 491 |
+
"MODEL_CONTENT": {item.evidence_id for item in content},
|
| 492 |
+
"INFERENCE_RUNTIME": {item.evidence_id for item in runtimes},
|
| 493 |
+
}
|
| 494 |
+
observation = self.observations.observe(
|
| 495 |
+
snapshot.identity, set().union(*supplied.values())
|
| 496 |
+
)
|
| 497 |
first_seen_ns = observation.first_seen_ns
|
| 498 |
# Both groups must be valid in this snapshot. Observations only
|
| 499 |
# provide bounded timing, never stale evidence joining.
|
| 500 |
detected = match(self.catalogue, snapshot, evidence=supplied)
|
| 501 |
if detected is None:
|
| 502 |
continue
|
| 503 |
+
qualified_ns = time.monotonic_ns()
|
| 504 |
try:
|
| 505 |
executable_sha256 = self._cached_executable_digest(snapshot)
|
| 506 |
except (JsonInputError, OSError):
|
|
|
|
| 513 |
self.discovery_active.add(snapshot.identity)
|
| 514 |
event_id = os.urandom(12).hex()
|
| 515 |
if synchronous:
|
| 516 |
+
self._enforce_discovery(
|
| 517 |
+
snapshot,
|
| 518 |
+
detected,
|
| 519 |
+
content,
|
| 520 |
+
runtimes,
|
| 521 |
+
first_seen_ns,
|
| 522 |
+
qualified_ns,
|
| 523 |
+
executable_sha256,
|
| 524 |
+
event_id,
|
| 525 |
+
)
|
| 526 |
else:
|
| 527 |
+
threading.Thread(
|
| 528 |
+
target=self._enforce_discovery,
|
| 529 |
+
args=(
|
| 530 |
+
snapshot,
|
| 531 |
+
detected,
|
| 532 |
+
content,
|
| 533 |
+
runtimes,
|
| 534 |
+
first_seen_ns,
|
| 535 |
+
qualified_ns,
|
| 536 |
+
executable_sha256,
|
| 537 |
+
event_id,
|
| 538 |
+
),
|
| 539 |
+
daemon=True,
|
| 540 |
+
).start()
|
| 541 |
|
| 542 |
def _discovery_loop(self) -> None:
|
| 543 |
while not self.stop_event.is_set():
|
|
|
|
| 549 |
|
| 550 |
def _cleanup(self, unit: str) -> dict[str, Any]:
|
| 551 |
result = self._run(["/usr/bin/systemctl", "stop", unit])
|
| 552 |
+
return {
|
| 553 |
+
"attempted": True,
|
| 554 |
+
"systemctl_stop_returncode": result.returncode,
|
| 555 |
+
"systemctl_stop_stderr": result.stderr.strip(),
|
| 556 |
+
}
|
| 557 |
|
| 558 |
def _write_receipt(self, receipt: dict[str, Any], event_id: str) -> None:
|
| 559 |
receipt["receipt_written_utc"] = dt.datetime.now(dt.UTC).isoformat().replace("+00:00", "Z")
|
| 560 |
self.operations.append("durable-receipt")
|
| 561 |
write_atomic(self._receipt_path(event_id), receipt)
|
| 562 |
|
| 563 |
+
def _contain(
|
| 564 |
+
self, record: dict[str, Any], trigger: str, trigger_ns: int | None = None
|
| 565 |
+
) -> dict[str, Any]:
|
| 566 |
"""Direct cgroup.kill is the first trigger-side effect; cleanup is post-proof only."""
|
| 567 |
lock = self._new_lock(record["run_id"])
|
| 568 |
with lock:
|
|
|
|
| 582 |
self._store(record)
|
| 583 |
raise JsonInputError(f"containment failed: {error}") from error
|
| 584 |
event_id = os.urandom(12).hex()
|
| 585 |
+
receipt = make_receipt(
|
| 586 |
+
record=record,
|
| 587 |
+
trigger=trigger,
|
| 588 |
+
trigger_ns=observed,
|
| 589 |
+
kill_started_ns=kill_started,
|
| 590 |
+
kill_complete_ns=kill_completed,
|
| 591 |
+
empty_ns=empty_ns,
|
| 592 |
+
proof=proof,
|
| 593 |
+
version=__version__,
|
| 594 |
+
source_commit=self.policy["source_commit"],
|
| 595 |
+
event_id=event_id,
|
| 596 |
+
)
|
| 597 |
try:
|
| 598 |
self._write_receipt(receipt, event_id)
|
| 599 |
record["state"] = "TERMINATED"
|
|
|
|
| 601 |
except Exception as error:
|
| 602 |
record["state"] = "CONTAINED_RECEIPT_FAILED"
|
| 603 |
self._store(record)
|
| 604 |
+
raise JsonInputError(
|
| 605 |
+
f"contained but receipt persistence failed: {error}"
|
| 606 |
+
) from error
|
| 607 |
# Cleanup is deliberately not in the enforcement or proof path.
|
| 608 |
cleanup = self._cleanup(record["unit"])
|
| 609 |
receipt["cleanup"] = cleanup
|
|
|
|
| 722 |
raise JsonInputError("max_pids must be from 4 to 4096")
|
| 723 |
with self.start_lock:
|
| 724 |
if name_path(self.names, name).exists() or self._active_exists():
|
| 725 |
+
raise JsonInputError(
|
| 726 |
+
"one protected workload is already active or name is unavailable"
|
| 727 |
+
)
|
| 728 |
run_id = os.urandom(12).hex()
|
| 729 |
unit = f"{UNIT_PREFIX}{run_id}.service"
|
| 730 |
gate = self._make_gate(run_id)
|
| 731 |
+
result = self._run(
|
| 732 |
+
[
|
| 733 |
+
"/usr/bin/systemd-run",
|
| 734 |
+
"--no-block",
|
| 735 |
+
f"--unit={unit}",
|
| 736 |
+
"--collect",
|
| 737 |
+
f"--uid={self.policy['workload_uid']}",
|
| 738 |
+
f"--gid={self.policy['workload_gid']}",
|
| 739 |
+
"--property=Type=exec",
|
| 740 |
+
"--property=ExitType=cgroup",
|
| 741 |
+
"--property=KillMode=control-group",
|
| 742 |
+
"--property=NoNewPrivileges=yes",
|
| 743 |
+
"--property=UMask=0077",
|
| 744 |
+
f"--property=TasksMax={maximum}",
|
| 745 |
+
"--",
|
| 746 |
+
"/usr/bin/python3",
|
| 747 |
+
"/usr/local/lib/lumi-eggcracker/lumi-eggcracker.pyz",
|
| 748 |
+
"_gate",
|
| 749 |
+
"--fifo",
|
| 750 |
+
str(gate),
|
| 751 |
+
"--",
|
| 752 |
+
*argv,
|
| 753 |
+
]
|
| 754 |
+
)
|
| 755 |
if result.returncode:
|
| 756 |
gate.unlink(missing_ok=True)
|
| 757 |
raise JsonInputError(result.stderr.strip() or "system workload launch failed")
|
|
|
|
| 766 |
if props.get("ActiveState") != "active" or not props.get("ControlGroup"):
|
| 767 |
raise JsonInputError("gated workload did not become active")
|
| 768 |
identity = capture_identity(props["ControlGroup"], run_id, unit)
|
| 769 |
+
record = {
|
| 770 |
+
**summary,
|
| 771 |
+
"boot_id": identity.boot_id,
|
| 772 |
+
"cgroup": identity.cgroup,
|
| 773 |
+
"cgroup_device": identity.device,
|
| 774 |
+
"cgroup_inode": identity.inode,
|
| 775 |
+
"created_monotonic_ns": time.monotonic_ns(),
|
| 776 |
+
"max_pids": maximum,
|
| 777 |
+
"name": name,
|
| 778 |
+
"operator_uid": self.operator_uid,
|
| 779 |
+
"run_id": run_id,
|
| 780 |
+
"schema_version": RUN_SCHEMA,
|
| 781 |
+
"state": "STARTING",
|
| 782 |
+
"unit": unit,
|
| 783 |
+
"workload_gid": self.policy["workload_gid"],
|
| 784 |
+
"workload_uid": self.policy["workload_uid"],
|
| 785 |
+
}
|
| 786 |
self._store(record)
|
| 787 |
ready = threading.Event()
|
| 788 |
watcher = threading.Thread(target=self._watch, args=(record, ready), daemon=True)
|
|
|
|
| 795 |
if record["state"] in ACTIVE_STATES:
|
| 796 |
record["state"] = "RUNNING"
|
| 797 |
self._store(record)
|
| 798 |
+
return {
|
| 799 |
+
"name": name,
|
| 800 |
+
"run_id": run_id,
|
| 801 |
+
"state": record["state"],
|
| 802 |
+
"unit": unit,
|
| 803 |
+
"workload_uid": record["workload_uid"],
|
| 804 |
+
}
|
| 805 |
except Exception:
|
| 806 |
gate.unlink(missing_ok=True)
|
| 807 |
try:
|
|
|
|
| 819 |
if not RUN_ID.fullmatch(run_id):
|
| 820 |
raise JsonInputError("orphan cgroup identity is invalid")
|
| 821 |
identity = capture_identity(cgroup, run_id, unit)
|
| 822 |
+
return {
|
| 823 |
+
"argv_count": 0,
|
| 824 |
+
"argv_sha256": "0" * 64,
|
| 825 |
+
"boot_id": identity.boot_id,
|
| 826 |
+
"cgroup": identity.cgroup,
|
| 827 |
+
"cgroup_device": identity.device,
|
| 828 |
+
"cgroup_inode": identity.inode,
|
| 829 |
+
"created_monotonic_ns": time.monotonic_ns(),
|
| 830 |
+
"executable": "<orphaned-owned-cgroup>",
|
| 831 |
+
"max_pids": 0,
|
| 832 |
+
"name": f"orphan-{run_id}",
|
| 833 |
+
"operator_uid": self.operator_uid,
|
| 834 |
+
"run_id": run_id,
|
| 835 |
+
"schema_version": RUN_SCHEMA,
|
| 836 |
+
"state": "RUNNING",
|
| 837 |
+
"unit": unit,
|
| 838 |
+
"workload_gid": self.policy["workload_gid"],
|
| 839 |
+
"workload_uid": self.policy["workload_uid"],
|
| 840 |
+
}
|
| 841 |
|
| 842 |
def _recover(self) -> None:
|
| 843 |
recorded_ids: set[str] = set()
|
|
|
|
| 857 |
continue
|
| 858 |
run_id = path.name.removeprefix(UNIT_PREFIX).removesuffix(".service")
|
| 859 |
if RUN_ID.fullmatch(run_id) and run_id not in recorded_ids:
|
| 860 |
+
self._contain(
|
| 861 |
+
self._orphan_record("/system.slice/" + path.name),
|
| 862 |
+
"SUPERVISOR_RESTART_FAIL_CLOSED",
|
| 863 |
+
)
|
| 864 |
|
| 865 |
def handle(self, value: dict[str, Any]) -> dict[str, Any]:
|
| 866 |
+
if (
|
| 867 |
+
set(value) != {"action", "args"}
|
| 868 |
+
or not isinstance(value["action"], str)
|
| 869 |
+
or not isinstance(value["args"], dict)
|
| 870 |
+
):
|
| 871 |
raise JsonInputError("request contract is invalid")
|
| 872 |
action, args = value["action"], value["args"]
|
| 873 |
if action == "doctor" and not args:
|
| 874 |
+
available = (
|
| 875 |
+
Path("/sys/fs/cgroup/cgroup.controllers").is_file()
|
| 876 |
+
and "pids"
|
| 877 |
+
in Path("/sys/fs/cgroup/cgroup.controllers").read_text(encoding="ascii").split()
|
| 878 |
+
)
|
| 879 |
ready = available and pidfd_available() and self.quarantine_root is not None
|
| 880 |
+
return {
|
| 881 |
+
"autonomous_discovery": ready,
|
| 882 |
+
"backend": "root-supervisor",
|
| 883 |
+
"catalogue": public_catalogue(self.catalogue),
|
| 884 |
+
"cgroup_v2": available,
|
| 885 |
+
"pidfd": pidfd_available(),
|
| 886 |
+
"result": "PASS" if ready else "UNSUPPORTED",
|
| 887 |
+
"version": __version__,
|
| 888 |
+
"workload_uid": self.policy["workload_uid"],
|
| 889 |
+
}
|
| 890 |
if action == "start":
|
| 891 |
return self._start(args)
|
| 892 |
if action == "status" and set(args) == {"name"}:
|
|
|
|
| 894 |
record = self._load(args["name"])
|
| 895 |
except JsonInputError:
|
| 896 |
record = self._latest_by_name(args["name"])
|
| 897 |
+
return {
|
| 898 |
+
"name": record["name"],
|
| 899 |
+
"run_id": record["run_id"],
|
| 900 |
+
"state": record["state"],
|
| 901 |
+
"unit": record["unit"],
|
| 902 |
+
"workload_uid": record["workload_uid"],
|
| 903 |
+
}
|
| 904 |
if action == "list" and not args:
|
| 905 |
+
runs = [
|
| 906 |
+
self.handle({"action": "status", "args": {"name": path.stem}})
|
| 907 |
+
for path in sorted(self.names.glob("*.json"))
|
| 908 |
+
]
|
| 909 |
return {"runs": runs}
|
| 910 |
if action == "approve" and set(args) == {"argv", "name", "uid"}:
|
| 911 |
+
value = create_approval(
|
| 912 |
+
self.approvals,
|
| 913 |
+
name=args["name"],
|
| 914 |
+
uid=args["uid"],
|
| 915 |
+
argv=args["argv"],
|
| 916 |
+
operator_uid=self.operator_uid,
|
| 917 |
+
)
|
| 918 |
return {"approval": public_approval(value), "result": "APPROVED"}
|
| 919 |
if action == "revoke" and set(args) == {"name"}:
|
| 920 |
return revoke(self.approvals, args["name"])
|
| 921 |
if action == "approvals" and not args:
|
| 922 |
+
return {
|
| 923 |
+
"approvals": [public_approval(value) for value in load_approvals(self.approvals)]
|
| 924 |
+
}
|
| 925 |
if action == "detections" and not args:
|
| 926 |
values: list[dict[str, Any]] = []
|
| 927 |
for path in sorted(self.detections.glob("*.json"), reverse=True):
|
| 928 |
try:
|
| 929 |
value = load_regular_json(path)
|
| 930 |
+
values.append(
|
| 931 |
+
{
|
| 932 |
+
key: value[key]
|
| 933 |
+
for key in ("detector", "event_id", "result", "trigger", "version")
|
| 934 |
+
}
|
| 935 |
+
)
|
| 936 |
except (JsonInputError, KeyError):
|
| 937 |
continue
|
| 938 |
return {"detections": values[:100]}
|
|
|
|
| 958 |
with connection:
|
| 959 |
connection.settimeout(3.0)
|
| 960 |
try:
|
| 961 |
+
_pid, uid, _gid = struct.unpack(
|
| 962 |
+
"3i", connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)
|
| 963 |
+
)
|
| 964 |
if uid not in {0, self.operator_uid}:
|
| 965 |
raise JsonInputError("peer uid is not authorized")
|
| 966 |
_send(connection, {"ok": True, "value": self.handle(_receive(connection))})
|
|
|
|
| 977 |
parser.add_argument("--policy", required=True, type=Path)
|
| 978 |
args = parser.parse_args(argv)
|
| 979 |
supervisor = Supervisor(args.policy)
|
| 980 |
+
|
| 981 |
def stop(*_: object) -> None:
|
| 982 |
supervisor.stop_event.set()
|
| 983 |
raise SystemExit(0)
|
tests/test_artifacts.py
CHANGED
|
@@ -27,14 +27,18 @@ class ArtifactTests(unittest.TestCase):
|
|
| 27 |
def test_bad_magic_version_and_impossible_counts_do_not_qualify(self) -> None:
|
| 28 |
with tempfile.TemporaryDirectory() as raw:
|
| 29 |
root = Path(raw)
|
| 30 |
-
for index, body in enumerate(
|
|
|
|
|
|
|
| 31 |
path = root / str(index)
|
| 32 |
path.write_bytes(body)
|
| 33 |
self.assertIsNone(validate_path(path))
|
| 34 |
|
| 35 |
def test_symlink_and_non_regular_files_do_not_qualify(self) -> None:
|
| 36 |
with tempfile.TemporaryDirectory() as raw:
|
| 37 |
-
root = Path(raw)
|
|
|
|
|
|
|
| 38 |
target.write_bytes(gguf())
|
| 39 |
try:
|
| 40 |
os.symlink(target, link)
|
|
|
|
| 27 |
def test_bad_magic_version_and_impossible_counts_do_not_qualify(self) -> None:
|
| 28 |
with tempfile.TemporaryDirectory() as raw:
|
| 29 |
root = Path(raw)
|
| 30 |
+
for index, body in enumerate(
|
| 31 |
+
(b"NOPE" + gguf()[4:], gguf(version=1), gguf(tensors=1_000_000, padding=1))
|
| 32 |
+
):
|
| 33 |
path = root / str(index)
|
| 34 |
path.write_bytes(body)
|
| 35 |
self.assertIsNone(validate_path(path))
|
| 36 |
|
| 37 |
def test_symlink_and_non_regular_files_do_not_qualify(self) -> None:
|
| 38 |
with tempfile.TemporaryDirectory() as raw:
|
| 39 |
+
root = Path(raw)
|
| 40 |
+
target = root / "target"
|
| 41 |
+
link = root / "link"
|
| 42 |
target.write_bytes(gguf())
|
| 43 |
try:
|
| 44 |
os.symlink(target, link)
|
tests/test_detectors.py
CHANGED
|
@@ -19,19 +19,32 @@ class DetectorTests(unittest.TestCase):
|
|
| 19 |
def test_llama_cpp_fast_path_requires_model_argument(self) -> None:
|
| 20 |
catalogue = load_bundled()
|
| 21 |
self.assertIsNone(match(catalogue, Sample("llama-cli", ("/usr/bin/llama-cli", "--help"))))
|
| 22 |
-
value = match(
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
def test_content_profile_requires_both_independent_groups(self) -> None:
|
| 26 |
catalogue = load_bundled()
|
| 27 |
sample = Sample("unfamiliar", ("anything",))
|
| 28 |
self.assertIsNone(match(catalogue, sample, evidence={"MODEL_CONTENT": {"gguf-v3"}}))
|
| 29 |
self.assertIsNone(match(catalogue, sample, evidence={"INFERENCE_RUNTIME": {"llama-elf"}}))
|
| 30 |
-
self.assertEqual(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
def test_generic_language_runtime_is_not_a_match(self) -> None:
|
| 33 |
catalogue = load_bundled()
|
| 34 |
-
self.assertIsNone(
|
|
|
|
|
|
|
| 35 |
self.assertIsNone(match(catalogue, Sample("node", ("node", "agent.js"))))
|
| 36 |
|
| 37 |
def test_catalogue_rejects_unknown_predicate_and_incomplete_content_group(self) -> None:
|
|
|
|
| 19 |
def test_llama_cpp_fast_path_requires_model_argument(self) -> None:
|
| 20 |
catalogue = load_bundled()
|
| 21 |
self.assertIsNone(match(catalogue, Sample("llama-cli", ("/usr/bin/llama-cli", "--help"))))
|
| 22 |
+
value = match(
|
| 23 |
+
catalogue, Sample("llama-cli", ("/usr/bin/llama-cli", "-m", "/models/tiny.gguf"))
|
| 24 |
+
)
|
| 25 |
+
self.assertEqual(
|
| 26 |
+
DetectionMatch("llama.cpp", "FAST_NAME", ("exe_basename", "argv_model_suffix")), value
|
| 27 |
+
)
|
| 28 |
|
| 29 |
def test_content_profile_requires_both_independent_groups(self) -> None:
|
| 30 |
catalogue = load_bundled()
|
| 31 |
sample = Sample("unfamiliar", ("anything",))
|
| 32 |
self.assertIsNone(match(catalogue, sample, evidence={"MODEL_CONTENT": {"gguf-v3"}}))
|
| 33 |
self.assertIsNone(match(catalogue, sample, evidence={"INFERENCE_RUNTIME": {"llama-elf"}}))
|
| 34 |
+
self.assertEqual(
|
| 35 |
+
DetectionMatch("content.gguf-llama", "CONTENT", ("gguf-v3", "llama-elf")),
|
| 36 |
+
match(
|
| 37 |
+
catalogue,
|
| 38 |
+
sample,
|
| 39 |
+
evidence={"MODEL_CONTENT": {"gguf-v3"}, "INFERENCE_RUNTIME": {"llama-elf"}},
|
| 40 |
+
),
|
| 41 |
+
)
|
| 42 |
|
| 43 |
def test_generic_language_runtime_is_not_a_match(self) -> None:
|
| 44 |
catalogue = load_bundled()
|
| 45 |
+
self.assertIsNone(
|
| 46 |
+
match(catalogue, Sample("python3", ("/usr/bin/python3", "worker.py", "--model", "cat")))
|
| 47 |
+
)
|
| 48 |
self.assertIsNone(match(catalogue, Sample("node", ("node", "agent.js"))))
|
| 49 |
|
| 50 |
def test_catalogue_rejects_unknown_predicate_and_incomplete_content_group(self) -> None:
|
tests/test_elfmarkers.py
CHANGED
|
@@ -13,15 +13,20 @@ def elf(*, markers: tuple[str, ...], append_decoys: bool = False) -> bytes:
|
|
| 13 |
names: list[int] = []
|
| 14 |
cursor = 1
|
| 15 |
for item in markers:
|
| 16 |
-
names.append(cursor)
|
|
|
|
| 17 |
body = bytearray(512 + max(24, len(markers) * 24))
|
| 18 |
body[:16] = b"\x7fELF\x02\x01\x01" + b"\0" * 9
|
| 19 |
body[16:64] = struct.pack("<HHIQQQIHHHHHH", 2, 62, 1, 0, 0, 64, 0, 64, 0, 0, 64, 3, 0)
|
| 20 |
body[64 + 64 : 64 + 128] = struct.pack("<IIQQQQIIQQ", 0, 3, 0, 0, 256, len(strings), 0, 0, 1, 0)
|
| 21 |
-
body[64 + 128 : 64 + 192] = struct.pack(
|
|
|
|
|
|
|
| 22 |
body[256 : 256 + len(strings)] = strings
|
| 23 |
for index, name in enumerate(names):
|
| 24 |
-
body[512 + index * 24 : 512 + (index + 1) * 24] = struct.pack(
|
|
|
|
|
|
|
| 25 |
if append_decoys:
|
| 26 |
body.extend(b"llama_decode\0llama_model_load_from_file\0")
|
| 27 |
return bytes(body)
|
|
@@ -41,8 +46,11 @@ class ElfMarkerTests(unittest.TestCase):
|
|
| 41 |
def test_one_marker_or_appended_marker_text_does_not_qualify(self) -> None:
|
| 42 |
with tempfile.TemporaryDirectory() as raw:
|
| 43 |
root = Path(raw)
|
| 44 |
-
for index, body in enumerate(
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
| 46 |
self.assertIsNone(inspect_path(path))
|
| 47 |
|
| 48 |
def test_build_id_fallback_is_explicitly_pinned(self) -> None:
|
|
|
|
| 13 |
names: list[int] = []
|
| 14 |
cursor = 1
|
| 15 |
for item in markers:
|
| 16 |
+
names.append(cursor)
|
| 17 |
+
cursor += len(item) + 1
|
| 18 |
body = bytearray(512 + max(24, len(markers) * 24))
|
| 19 |
body[:16] = b"\x7fELF\x02\x01\x01" + b"\0" * 9
|
| 20 |
body[16:64] = struct.pack("<HHIQQQIHHHHHH", 2, 62, 1, 0, 0, 64, 0, 64, 0, 0, 64, 3, 0)
|
| 21 |
body[64 + 64 : 64 + 128] = struct.pack("<IIQQQQIIQQ", 0, 3, 0, 0, 256, len(strings), 0, 0, 1, 0)
|
| 22 |
+
body[64 + 128 : 64 + 192] = struct.pack(
|
| 23 |
+
"<IIQQQQIIQQ", 0, 2, 0, 0, 512, len(markers) * 24, 1, 0, 8, 24
|
| 24 |
+
)
|
| 25 |
body[256 : 256 + len(strings)] = strings
|
| 26 |
for index, name in enumerate(names):
|
| 27 |
+
body[512 + index * 24 : 512 + (index + 1) * 24] = struct.pack(
|
| 28 |
+
"<IBBHQQ", name, 0, 0, 1, 0, 0
|
| 29 |
+
)
|
| 30 |
if append_decoys:
|
| 31 |
body.extend(b"llama_decode\0llama_model_load_from_file\0")
|
| 32 |
return bytes(body)
|
|
|
|
| 46 |
def test_one_marker_or_appended_marker_text_does_not_qualify(self) -> None:
|
| 47 |
with tempfile.TemporaryDirectory() as raw:
|
| 48 |
root = Path(raw)
|
| 49 |
+
for index, body in enumerate(
|
| 50 |
+
(elf(markers=("llama_decode",)), elf(markers=(), append_decoys=True), b"not an elf")
|
| 51 |
+
):
|
| 52 |
+
path = root / str(index)
|
| 53 |
+
path.write_bytes(body)
|
| 54 |
self.assertIsNone(inspect_path(path))
|
| 55 |
|
| 56 |
def test_build_id_fallback_is_explicitly_pinned(self) -> None:
|