Spaces:
Running
Running
feat: add name-independent GGUF recognition
Browse files- CHANGELOG.md +6 -0
- LIMITATIONS.md +1 -1
- QUALIFICATION.md +2 -2
- README.md +8 -7
- RELEASE_NOTES.md +2 -2
- SECURITY_MODEL.md +2 -2
- pyproject.toml +1 -1
- scripts/build_release.py +1 -0
- scripts/install.py +2 -2
- scripts/prepare_ai_smoke.py +1 -1
- scripts/smoke_content_ai.py +163 -0
- scripts/verify_release.py +2 -2
- src/lumi_eggcracker/__init__.py +1 -1
- src/lumi_eggcracker/artifacts.py +148 -0
- src/lumi_eggcracker/detector_catalogue.json +1 -1
- src/lumi_eggcracker/detectors.py +88 -30
- src/lumi_eggcracker/discovery.py +33 -2
- src/lumi_eggcracker/elfmarkers.py +105 -0
- src/lumi_eggcracker/observation.py +40 -0
- src/lumi_eggcracker/supervisor.py +33 -11
- tests/test_artifacts.py +43 -0
- tests/test_cli.py +1 -1
- tests/test_detectors.py +17 -8
- tests/test_elfmarkers.py +46 -0
- tests/test_observation.py +17 -0
CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
| 1 |
# Changelog
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
## 0.2.0
|
| 4 |
|
| 5 |
- Add deterministic autonomous discovery of unapproved supported AI runtimes.
|
|
|
|
| 1 |
# Changelog
|
| 2 |
|
| 3 |
+
## 0.3.0
|
| 4 |
+
|
| 5 |
+
- Add bounded name-independent `content.gguf-llama` recognition from validated GGUF content and two ELF runtime markers.
|
| 6 |
+
- Keep exact approvals and immediate pidfd-stop/cgroup-kill enforcement for content matches.
|
| 7 |
+
- Add redacted content-path detection receipts and renamed-runner content smoke tooling.
|
| 8 |
+
|
| 9 |
## 0.2.0
|
| 10 |
|
| 11 |
- Add deterministic autonomous discovery of unapproved supported AI runtimes.
|
LIMITATIONS.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# Limitations
|
| 2 |
|
| 3 |
-
Lumi Eggcracker 0.
|
| 4 |
|
| 5 |
The observer uses bounded `/proc` polling. It has no kernel execution hook, eBPF programme or guarantee that a process which forks, daemonises or exits before discovery can be reconstructed as one complete historical tree. A successful receipt proves the exact captured quarantine cgroup is empty.
|
| 6 |
|
|
|
|
| 1 |
# Limitations
|
| 2 |
|
| 3 |
+
Lumi Eggcracker 0.3.0 autonomously acts only on a complete match from its installed deterministic AI-runtime catalogue. Its content path currently supports only a regular GGUF v2/v3 artifact combined with a qualified llama.cpp/GGML ELF runtime exposing two valid symbol-table markers. It does not recognise arbitrary, custom, fully stripped, encrypted, containerised, remote or otherwise unlisted AI/agent workloads.
|
| 4 |
|
| 5 |
The observer uses bounded `/proc` polling. It has no kernel execution hook, eBPF programme or guarantee that a process which forks, daemonises or exits before discovery can be reconstructed as one complete historical tree. A successful receipt proves the exact captured quarantine cgroup is empty.
|
| 6 |
|
QUALIFICATION.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
# Qualification
|
| 2 |
|
| 3 |
-
The 0.
|
| 4 |
|
| 5 |
Mandatory autonomous gates are: 100/100 unapproved fixture discoveries and complete tree kills, 100/100 unrelated-canary survivals, zero surviving bounded replacement attempts, zero reused-PID signals, 50/50 exact approved survivals, zero kills in the benign and partial-match matrices, zero workload policy/socket accesses, restart recovery, p95 qualifying-snapshot-to-stop below 100 ms, p95 fixture-start-to-stop below 500 ms, and p95 trigger-to-empty below 500 ms.
|
| 6 |
|
| 7 |
-
The candidate must also run five unapproved/approved/unapproved real llama.cpp/Qwen
|
|
|
|
| 1 |
# Qualification
|
| 2 |
|
| 3 |
+
The 0.3.0 candidate is releasable only when its exact commit passes direct tests, the existing selected-workload matrix, the native autonomous-discovery matrix, and the content-recognition matrix on one Ubuntu VM.
|
| 4 |
|
| 5 |
Mandatory autonomous gates are: 100/100 unapproved fixture discoveries and complete tree kills, 100/100 unrelated-canary survivals, zero surviving bounded replacement attempts, zero reused-PID signals, 50/50 exact approved survivals, zero kills in the benign and partial-match matrices, zero workload policy/socket accesses, restart recovery, p95 qualifying-snapshot-to-stop below 100 ms, p95 fixture-start-to-stop below 500 ms, and p95 trigger-to-empty below 500 ms.
|
| 6 |
|
| 7 |
+
The candidate must also run five renamed-runner, extensionless-model unapproved/approved/unapproved real llama.cpp/Qwen content sequences, 100 renamed content fixture kills, 100 canary survivals, 50 exact disguised approvals and at least 300 benign model-handling launches with zero kills. It must cleanly install with discovery armed and completely uninstall. Evidence is specific to the tested commit and host; it does not establish universal AI identification.
|
README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
|
| 3 |
Lumi Eggcracker is a local Linux kill switch for unapproved, supported AI and agent runtimes.
|
| 4 |
|
| 5 |
-
> Eggcracker monitors a Linux host for
|
| 6 |
|
| 7 |
There is no alert-only phase for an unapproved catalogue match. Containment begins with a pidfd stop signal; the explanation and receipt are written only after cgroup containment completes.
|
| 8 |
|
|
@@ -10,6 +10,7 @@ There is no alert-only phase for an unapproved catalogue match. Containment begi
|
|
| 10 |
|
| 11 |
- continuously scans host processes and performs a startup scan before accepting control commands;
|
| 12 |
- detects published local-runtime profiles including llama.cpp, Ollama, vLLM, Text Generation Inference, LocalAI, llamafile and selected agent CLIs;
|
|
|
|
| 13 |
- lets the configured operator approve one exact executable, UID and invocation before it is run;
|
| 14 |
- automatically stops, captures and kills unapproved matches with `pidfd_send_signal` and cgroup-v2 `cgroup.kill`;
|
| 15 |
- preserves the existing protected `start` and operator `kill` workflow;
|
|
@@ -17,7 +18,7 @@ There is no alert-only phase for an unapproved catalogue match. Containment begi
|
|
| 17 |
|
| 18 |
## What it does not do
|
| 19 |
|
| 20 |
-
Eggcracker does not identify every possible AI implementation.
|
| 21 |
|
| 22 |
A successful receipt proves the captured quarantine cgroup is empty. It does not prove that a process which escaped before detection never existed.
|
| 23 |
|
|
@@ -30,16 +31,16 @@ A successful receipt proves the captured quarantine cgroup is empty. It does not
|
|
| 30 |
|
| 31 |
## Quick start
|
| 32 |
|
| 33 |
-
Download and extract `lumi-eggcracker-0.
|
| 34 |
|
| 35 |
```sh
|
| 36 |
-
cd lumi-eggcracker-0.
|
| 37 |
-
sudo python3 scripts/install.py --operator "$USER" --artifact ./lumi-eggcracker-0.
|
| 38 |
eggcracker doctor
|
| 39 |
eggcracker approvals
|
| 40 |
```
|
| 41 |
|
| 42 |
-
An unapproved
|
| 43 |
|
| 44 |
```sh
|
| 45 |
eggcracker approve --name local-qwen --uid "$(id -u)" -- \
|
|
@@ -72,7 +73,7 @@ sudo python3 scripts/smoke_autonomous_ai.py \
|
|
| 72 |
--user "$USER" --repetitions 5 --output ./autonomous-ai-smoke.json
|
| 73 |
```
|
| 74 |
|
| 75 |
-
The smoke launches the model directly, outside `eggcracker start`, verifies that Eggcracker kills the unapproved invocation, then proves that the same exact invocation survives only when approved.
|
| 76 |
|
| 77 |
To remove Eggcracker completely:
|
| 78 |
|
|
|
|
| 2 |
|
| 3 |
Lumi Eggcracker is a local Linux kill switch for unapproved, supported AI and agent runtimes.
|
| 4 |
|
| 5 |
+
> Eggcracker monitors a Linux host for supported local AI inference workloads. It recognises installed fast-name profiles and, for qualified GGUF/llama.cpp combinations, validated model content plus inference-runtime binary evidence. When a complete match has no exact operator approval, it automatically stops the process, captures its discovered process tree in a root-owned cgroup, and kills that cgroup.
|
| 6 |
|
| 7 |
There is no alert-only phase for an unapproved catalogue match. Containment begins with a pidfd stop signal; the explanation and receipt are written only after cgroup containment completes.
|
| 8 |
|
|
|
|
| 10 |
|
| 11 |
- continuously scans host processes and performs a startup scan before accepting control commands;
|
| 12 |
- detects published local-runtime profiles including llama.cpp, Ollama, vLLM, Text Generation Inference, LocalAI, llamafile and selected agent CLIs;
|
| 13 |
+
- recognises the qualified `content.gguf-llama` profile without depending on executable or model filename: a structurally valid GGUF v2/v3 artifact and two llama.cpp/GGML ELF runtime markers are both required;
|
| 14 |
- lets the configured operator approve one exact executable, UID and invocation before it is run;
|
| 15 |
- automatically stops, captures and kills unapproved matches with `pidfd_send_signal` and cgroup-v2 `cgroup.kill`;
|
| 16 |
- preserves the existing protected `start` and operator `kill` workflow;
|
|
|
|
| 18 |
|
| 19 |
## What it does not do
|
| 20 |
|
| 21 |
+
Eggcracker does not identify every possible AI implementation. Content recognition currently excludes stripped or bespoke runtimes without the qualified markers, custom/encrypted model formats, containerised and remote API-only workloads. It does not claim general malware or intrusion detection. It does not use a behavioural model, isolate host networking, credentials or filesystems, or replace EDR.
|
| 22 |
|
| 23 |
A successful receipt proves the captured quarantine cgroup is empty. It does not prove that a process which escaped before detection never existed.
|
| 24 |
|
|
|
|
| 31 |
|
| 32 |
## Quick start
|
| 33 |
|
| 34 |
+
Download and extract `lumi-eggcracker-0.3.0-linux.zip`, then run as root:
|
| 35 |
|
| 36 |
```sh
|
| 37 |
+
cd lumi-eggcracker-0.3.0
|
| 38 |
+
sudo python3 scripts/install.py --operator "$USER" --artifact ./lumi-eggcracker-0.3.0.pyz
|
| 39 |
eggcracker doctor
|
| 40 |
eggcracker approvals
|
| 41 |
```
|
| 42 |
|
| 43 |
+
An unapproved complete fast-name or content profile is killed automatically when it starts; Eggcracker does not pause for confirmation. To allow a known invocation, approve it before launch. The approval stores hashes, not its raw arguments:
|
| 44 |
|
| 45 |
```sh
|
| 46 |
eggcracker approve --name local-qwen --uid "$(id -u)" -- \
|
|
|
|
| 73 |
--user "$USER" --repetitions 5 --output ./autonomous-ai-smoke.json
|
| 74 |
```
|
| 75 |
|
| 76 |
+
The smoke launches the model directly, outside `eggcracker start`, verifies that Eggcracker kills the unapproved invocation, then proves that the same exact invocation survives only when approved. The companion `smoke_content_ai.py` uses a renamed runner, unfamiliar wrapper and extensionless GGUF path to exercise the content profile.
|
| 77 |
|
| 78 |
To remove Eggcracker completely:
|
| 79 |
|
RELEASE_NOTES.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
-
# Lumi Eggcracker 0.
|
| 2 |
|
| 3 |
-
0.
|
| 4 |
|
| 5 |
The release remains a Linux engineering preview. It does not claim universal AI recognition, behavioural detection, network isolation, malware prevention or EDR replacement. The existing real-AI assets remain external and are not distributed in release archives.
|
|
|
|
| 1 |
+
# Lumi Eggcracker 0.3.0
|
| 2 |
|
| 3 |
+
0.3.0 adds the qualified `content.gguf-llama` profile. It recognises a locally opened, structurally valid GGUF v2/v3 model alongside two llama.cpp/GGML ELF symbol markers. Neither the executable name nor model filename is required for this content path. Complete unapproved matches use the existing exact-approval, pidfd-stop, cgroup-capture and direct `cgroup.kill` sequence.
|
| 4 |
|
| 5 |
The release remains a Linux engineering preview. It does not claim universal AI recognition, behavioural detection, network isolation, malware prevention or EDR replacement. The existing real-AI assets remain external and are not distributed in release archives.
|
SECURITY_MODEL.md
CHANGED
|
@@ -2,8 +2,8 @@
|
|
| 2 |
|
| 3 |
The root-owned `lumi-eggcracker.service` is the only enforcement component. It reads the root-owned detector catalogue, observes bounded process facts from `/proc`, and accepts control requests only from root or the configured operator UID over a root-owned Unix socket. A workload account remains a dedicated no-login unprivileged user with no supplementary groups and cannot access the control socket.
|
| 4 |
|
| 5 |
-
For an unapproved complete catalogue match, Eggcracker revalidates PID plus start-time identity, sends `SIGSTOP` through a pidfd, stops descendants, moves the discovered tree into an exact child cgroup delegated to the supervisor, and writes `1` to `cgroup.kill`. It proves that cgroup hierarchy is empty before writing the detection receipt. Individual pidfd signals are the initial stop/capture mechanism; direct cgroup-v2 `cgroup.kill` remains the authoritative complete-tree kill primitive.
|
| 6 |
|
| 7 |
An approval is an exact root-owned record of a UID, resolved executable device/inode and digest, plus complete argv digest. Raw process arguments and environment values are not written to approval or detection records.
|
| 8 |
|
| 9 |
-
This is not a general sandbox, universal AI detector, host intrusion detector, malware detector, network isolator, credential isolator or EDR replacement. An unapproved workload can evade
|
|
|
|
| 2 |
|
| 3 |
The root-owned `lumi-eggcracker.service` is the only enforcement component. It reads the root-owned detector catalogue, observes bounded process facts from `/proc`, and accepts control requests only from root or the configured operator UID over a root-owned Unix socket. A workload account remains a dedicated no-login unprivileged user with no supplementary groups and cannot access the control socket.
|
| 4 |
|
| 5 |
+
For an unapproved complete catalogue match, Eggcracker revalidates PID plus start-time identity, sends `SIGSTOP` through a pidfd, stops descendants, moves the discovered tree into an exact child cgroup delegated to the supervisor, and writes `1` to `cgroup.kill`. Content profiles require two independently validated groups in the same process snapshot: bounded model content and bounded runtime binary evidence. It proves that cgroup hierarchy is empty before writing the detection receipt. Individual pidfd signals are the initial stop/capture mechanism; direct cgroup-v2 `cgroup.kill` remains the authoritative complete-tree kill primitive.
|
| 6 |
|
| 7 |
An approval is an exact root-owned record of a UID, resolved executable device/inode and digest, plus complete argv digest. Raw process arguments and environment values are not written to approval or detection records.
|
| 8 |
|
| 9 |
+
This is not a general sandbox, universal AI detector, host intrusion detector, malware detector, network isolator, credential isolator or EDR replacement. An unapproved workload can evade detection by using an unsupported content/runtime combination; the qualified content path is intentionally narrow and that boundary is documented rather than hidden.
|
pyproject.toml
CHANGED
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
| 4 |
|
| 5 |
[project]
|
| 6 |
name = "lumi-eggcracker"
|
| 7 |
-
version = "0.
|
| 8 |
description = "A local Linux kill switch for unapproved supported AI and agent runtimes"
|
| 9 |
readme = "README.md"
|
| 10 |
requires-python = ">=3.11"
|
|
|
|
| 4 |
|
| 5 |
[project]
|
| 6 |
name = "lumi-eggcracker"
|
| 7 |
+
version = "0.3.0"
|
| 8 |
description = "A local Linux kill switch for unapproved supported AI and agent runtimes"
|
| 9 |
readme = "README.md"
|
| 10 |
requires-python = ">=3.11"
|
scripts/build_release.py
CHANGED
|
@@ -81,6 +81,7 @@ def main() -> int:
|
|
| 81 |
ROOT / "scripts" / "ai_smoke_worker.py": "scripts/ai_smoke_worker.py",
|
| 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" / "run_autonomous_matrix.py": "scripts/run_autonomous_matrix.py",
|
| 85 |
}
|
| 86 |
with zipfile.ZipFile(bundle, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
|
|
|
|
| 81 |
ROOT / "scripts" / "ai_smoke_worker.py": "scripts/ai_smoke_worker.py",
|
| 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:
|
scripts/install.py
CHANGED
|
@@ -18,7 +18,7 @@ import zipfile
|
|
| 18 |
from pathlib import Path
|
| 19 |
from typing import Any
|
| 20 |
|
| 21 |
-
VERSION = "0.
|
| 22 |
LIB = Path("/usr/local/lib/lumi-eggcracker")
|
| 23 |
BIN = Path("/usr/local/bin/eggcracker")
|
| 24 |
ETC = Path("/etc/lumi-eggcracker")
|
|
@@ -117,7 +117,7 @@ def catalogue_from_artifact(artifact: Path) -> bytes:
|
|
| 117 |
parsed = json.loads(value.decode("utf-8"))
|
| 118 |
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
| 119 |
raise RuntimeError("detector catalogue is invalid") from error
|
| 120 |
-
if not isinstance(parsed, dict) or parsed.get("schema_version") != "lumi-eggcracker.detectors.
|
| 121 |
raise RuntimeError("detector catalogue schema is invalid")
|
| 122 |
return value
|
| 123 |
|
|
|
|
| 18 |
from pathlib import Path
|
| 19 |
from typing import Any
|
| 20 |
|
| 21 |
+
VERSION = "0.3.0"
|
| 22 |
LIB = Path("/usr/local/lib/lumi-eggcracker")
|
| 23 |
BIN = Path("/usr/local/bin/eggcracker")
|
| 24 |
ETC = Path("/etc/lumi-eggcracker")
|
|
|
|
| 117 |
parsed = json.loads(value.decode("utf-8"))
|
| 118 |
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
| 119 |
raise RuntimeError("detector catalogue is invalid") from error
|
| 120 |
+
if not isinstance(parsed, dict) or parsed.get("schema_version") != "lumi-eggcracker.detectors.v2":
|
| 121 |
raise RuntimeError("detector catalogue schema is invalid")
|
| 122 |
return value
|
| 123 |
|
scripts/prepare_ai_smoke.py
CHANGED
|
@@ -130,7 +130,7 @@ def download_model(destination: Path) -> None:
|
|
| 130 |
temporary.unlink(missing_ok=True)
|
| 131 |
value = hashlib.sha256()
|
| 132 |
size = 0
|
| 133 |
-
request = urllib.request.Request(MODEL_URL, headers={"User-Agent": "Lumi-Eggcracker-0.
|
| 134 |
try:
|
| 135 |
with urllib.request.urlopen(request, timeout=60) as response, temporary.open("xb") as handle:
|
| 136 |
if not response.url.startswith("https://"):
|
|
|
|
| 130 |
temporary.unlink(missing_ok=True)
|
| 131 |
value = hashlib.sha256()
|
| 132 |
size = 0
|
| 133 |
+
request = urllib.request.Request(MODEL_URL, headers={"User-Agent": "Lumi-Eggcracker-0.3.0"})
|
| 134 |
try:
|
| 135 |
with urllib.request.urlopen(request, timeout=60) as response, temporary.open("xb") as handle:
|
| 136 |
if not response.url.startswith("https://"):
|
scripts/smoke_content_ai.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exercise name-independent GGUF/llama.cpp recognition with real local AI."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import pwd
|
| 10 |
+
import secrets
|
| 11 |
+
import shutil
|
| 12 |
+
import signal
|
| 13 |
+
import subprocess
|
| 14 |
+
import tempfile
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
DETECTIONS = Path("/var/lib/lumi-eggcracker/detections")
|
| 20 |
+
CLI = "/usr/local/bin/eggcracker"
|
| 21 |
+
ASSET_SCHEMA = "lumi-eggcracker.ai-smoke-assets.v1"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def digest(path: Path) -> str:
|
| 25 |
+
value = hashlib.sha256()
|
| 26 |
+
with path.open("rb") as handle:
|
| 27 |
+
for block in iter(lambda: handle.read(64 * 1024), b""):
|
| 28 |
+
value.update(block)
|
| 29 |
+
return value.hexdigest()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def assets(path: Path) -> tuple[Path, Path, dict[str, Any]]:
|
| 33 |
+
value = json.loads(path.read_text(encoding="utf-8"))
|
| 34 |
+
if set(value) != {"llama", "model", "platform", "schema_version"} or value["schema_version"] != ASSET_SCHEMA:
|
| 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(runner, os.X_OK):
|
| 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")
|
| 41 |
+
return runner, model, value
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def control(user: str, argv: list[str]) -> dict[str, Any]:
|
| 45 |
+
result = subprocess.run(["/usr/sbin/runuser", "-u", user, "--", CLI, *argv], capture_output=True, text=True, check=False, timeout=30)
|
| 46 |
+
if result.returncode:
|
| 47 |
+
raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "Eggcracker control command failed")
|
| 48 |
+
value = json.loads(result.stdout)
|
| 49 |
+
if not isinstance(value, dict):
|
| 50 |
+
raise TypeError("Eggcracker control command returned invalid JSON")
|
| 51 |
+
return value
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def stop(process: subprocess.Popen[bytes] | None) -> None:
|
| 55 |
+
if process is not None and process.poll() is None:
|
| 56 |
+
os.killpg(process.pid, signal.SIGKILL)
|
| 57 |
+
process.wait(timeout=5)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def receipt_after(before: set[Path], *, timeout: float = 90) -> dict[str, Any]:
|
| 61 |
+
deadline = time.monotonic() + timeout
|
| 62 |
+
while time.monotonic() < deadline:
|
| 63 |
+
paths = set(DETECTIONS.glob("*.json")) - before
|
| 64 |
+
if paths:
|
| 65 |
+
value = json.loads(max(paths, key=lambda item: item.stat().st_mtime_ns).read_text(encoding="utf-8"))
|
| 66 |
+
if value.get("result") != "TERMINATED":
|
| 67 |
+
raise RuntimeError(f"content containment failed: {value.get('error', value.get('result'))}")
|
| 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 [str(runner), "-m", str(model), "-p", "Name a Linux cgroup property.", "-n", "4096", "-t", "12", "-tb", "12", "-c", "512", "--simple-io", "--single-turn", "--no-warmup", "--no-display-prompt", "--seed", "1234"]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def launch(user: str, wrapper: Path, argv: list[str], output: Path) -> subprocess.Popen[bytes]:
|
| 78 |
+
handle = output.open("wb")
|
| 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(["/usr/sbin/runuser", "-u", user, "--", "/usr/bin/python3", str(wrapper), *argv], stdout=handle, stderr=subprocess.DEVNULL, start_new_session=True)
|
| 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); os.chmod(root, 0o755)
|
| 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); os.chmod(disguised_runner, 0o755)
|
| 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 {"llama-cli", "llama-server", "main"}:
|
| 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
|
| 105 |
+
allowed: subprocess.Popen[bytes] | None = None
|
| 106 |
+
name = f"content-{index}-{secrets.token_hex(4)}"
|
| 107 |
+
try:
|
| 108 |
+
before = set(DETECTIONS.glob("*.json"))
|
| 109 |
+
unapproved = launch(user, wrapper, final_argv, output)
|
| 110 |
+
first = receipt_after(before)
|
| 111 |
+
stop(unapproved); unapproved = None
|
| 112 |
+
if first.get("detector", {}).get("profile") != "content.gguf-llama" or first.get("detector", {}).get("detection_path") != "CONTENT" or canary.poll() is not None:
|
| 113 |
+
raise RuntimeError("content profile or canary proof failed")
|
| 114 |
+
if str(disguised_model) in json.dumps(first, sort_keys=True) or str(wrapper) in json.dumps(first, sort_keys=True):
|
| 115 |
+
raise RuntimeError("content receipt leaked a local model or wrapper path")
|
| 116 |
+
approved = control(user, ["approve", "--name", name, "--uid", str(pwd.getpwnam(user).pw_uid), "--", *final_argv])
|
| 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 (not output.is_file() or output.stat().st_size < 32):
|
| 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); allowed = None
|
| 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); unapproved = None
|
| 132 |
+
if second.get("detector", {}).get("profile") != "content.gguf-llama" or canary.poll() is not None:
|
| 133 |
+
raise RuntimeError("revoked disguised AI was not terminated")
|
| 134 |
+
return {"approved_generated_bytes": generated, "first_receipt": first, "result": "PASS", "second_receipt": second}
|
| 135 |
+
finally:
|
| 136 |
+
stop(unapproved); stop(allowed); stop(canary)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def main() -> int:
|
| 140 |
+
if os.geteuid() != 0:
|
| 141 |
+
raise SystemExit("content AI smoke must run as root")
|
| 142 |
+
parser = argparse.ArgumentParser()
|
| 143 |
+
parser.add_argument("--assets-manifest", required=True, type=Path)
|
| 144 |
+
parser.add_argument("--user", required=True)
|
| 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 args.repetitions != 5 or args.output.exists() or args.output.is_symlink() or not args.output.parent.is_dir():
|
| 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(json.dumps({"repetitions": values, "result": "PASS"}, sort_keys=True) + "\n", encoding="utf-8")
|
| 155 |
+
return 0
|
| 156 |
+
except (OSError, RuntimeError, TypeError, json.JSONDecodeError) as error:
|
| 157 |
+
if not args.output.exists():
|
| 158 |
+
args.output.write_text(json.dumps({"error": str(error), "result": "FAIL"}, sort_keys=True) + "\n", encoding="utf-8")
|
| 159 |
+
raise SystemExit(f"content AI smoke failed: {error}") from error
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
if __name__ == "__main__":
|
| 163 |
+
raise SystemExit(main())
|
scripts/verify_release.py
CHANGED
|
@@ -10,7 +10,7 @@ import sys
|
|
| 10 |
import zipfile
|
| 11 |
from pathlib import Path
|
| 12 |
|
| 13 |
-
VERSION = "0.
|
| 14 |
PREFIX = f"lumi-eggcracker-{VERSION}/"
|
| 15 |
FORBIDDEN = (
|
| 16 |
"/mnt/" + "f/", "f" + ":\\", "network" + "-deny", "network" + "_rule",
|
|
@@ -47,7 +47,7 @@ def main() -> int:
|
|
| 47 |
manifest = json.loads((args.artifact.parent / "release-manifest.json").read_text(encoding="utf-8"))
|
| 48 |
if manifest.get("version") != VERSION or manifest.get("artifact") != args.artifact.name:
|
| 49 |
raise SystemExit("release manifest is inconsistent")
|
| 50 |
-
expected = {PREFIX + name for name in (args.artifact.name, args.source_archive.name, "release-manifest.json", "SHA256SUMS", "README.md", "LICENSE", "LIMITATIONS.md", "SECURITY.md", "SECURITY_MODEL.md", "QUALIFICATION.md", "RELEASE_NOTES.md", "scripts/install.py", "scripts/uninstall.py", "scripts/verify_uninstalled.py", "scripts/prepare_ai_smoke.py", "scripts/ai_smoke_worker.py", "scripts/smoke_local_ai.py", "scripts/smoke_autonomous_ai.py", "scripts/run_autonomous_matrix.py")}
|
| 51 |
with zipfile.ZipFile(args.release_bundle) as archive:
|
| 52 |
if set(archive.namelist()) != expected:
|
| 53 |
raise SystemExit("release bundle contents are inconsistent")
|
|
|
|
| 10 |
import zipfile
|
| 11 |
from pathlib import Path
|
| 12 |
|
| 13 |
+
VERSION = "0.3.0"
|
| 14 |
PREFIX = f"lumi-eggcracker-{VERSION}/"
|
| 15 |
FORBIDDEN = (
|
| 16 |
"/mnt/" + "f/", "f" + ":\\", "network" + "-deny", "network" + "_rule",
|
|
|
|
| 47 |
manifest = json.loads((args.artifact.parent / "release-manifest.json").read_text(encoding="utf-8"))
|
| 48 |
if manifest.get("version") != VERSION or manifest.get("artifact") != args.artifact.name:
|
| 49 |
raise SystemExit("release manifest is inconsistent")
|
| 50 |
+
expected = {PREFIX + name for name in (args.artifact.name, args.source_archive.name, "release-manifest.json", "SHA256SUMS", "README.md", "LICENSE", "LIMITATIONS.md", "SECURITY.md", "SECURITY_MODEL.md", "QUALIFICATION.md", "RELEASE_NOTES.md", "scripts/install.py", "scripts/uninstall.py", "scripts/verify_uninstalled.py", "scripts/prepare_ai_smoke.py", "scripts/ai_smoke_worker.py", "scripts/smoke_local_ai.py", "scripts/smoke_autonomous_ai.py", "scripts/smoke_content_ai.py", "scripts/run_autonomous_matrix.py")}
|
| 51 |
with zipfile.ZipFile(args.release_bundle) as archive:
|
| 52 |
if set(archive.namelist()) != expected:
|
| 53 |
raise SystemExit("release bundle contents are inconsistent")
|
src/lumi_eggcracker/__init__.py
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
"""Lumi Eggcracker: autonomous Linux AI-runtime containment."""
|
| 2 |
|
| 3 |
-
__version__ = "0.
|
|
|
|
| 1 |
"""Lumi Eggcracker: autonomous Linux AI-runtime containment."""
|
| 2 |
|
| 3 |
+
__version__ = "0.3.0"
|
src/lumi_eggcracker/artifacts.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bounded, content-based local model artifact recognition."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import os
|
| 7 |
+
import stat
|
| 8 |
+
import struct
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from .jsonio import JsonInputError
|
| 13 |
+
|
| 14 |
+
MAX_ARTIFACT_BYTES = 1 * 1024 * 1024
|
| 15 |
+
MAX_ARTIFACTS = 16
|
| 16 |
+
MAX_TOTAL_BYTES = 4 * 1024 * 1024
|
| 17 |
+
MAX_GGUF_ITEMS = 10_000_000
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass(frozen=True)
|
| 21 |
+
class ArtifactEvidence:
|
| 22 |
+
"""Redacted evidence suitable for a detection receipt."""
|
| 23 |
+
|
| 24 |
+
evidence_id: str
|
| 25 |
+
format: str
|
| 26 |
+
device: int
|
| 27 |
+
inode: int
|
| 28 |
+
size: int
|
| 29 |
+
header_sha256: str
|
| 30 |
+
|
| 31 |
+
def public(self) -> dict[str, object]:
|
| 32 |
+
return {
|
| 33 |
+
"format": self.format,
|
| 34 |
+
"header_sha256": self.header_sha256,
|
| 35 |
+
"size_bucket": _size_bucket(self.size),
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _size_bucket(size: int) -> str:
|
| 40 |
+
if size < 1 << 20:
|
| 41 |
+
return "<1MiB"
|
| 42 |
+
if size < 1 << 30:
|
| 43 |
+
return "1MiB-1GiB"
|
| 44 |
+
if size < 8 << 30:
|
| 45 |
+
return "1GiB-8GiB"
|
| 46 |
+
return ">=8GiB"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _regular(descriptor: int) -> os.stat_result:
|
| 50 |
+
metadata = os.fstat(descriptor)
|
| 51 |
+
if not stat.S_ISREG(metadata.st_mode) or metadata.st_size < 25:
|
| 52 |
+
raise JsonInputError("candidate model artifact is not a usable regular file")
|
| 53 |
+
return metadata
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _read_exact(descriptor: int, amount: int) -> bytes:
|
| 57 |
+
os.lseek(descriptor, 0, os.SEEK_SET)
|
| 58 |
+
value = bytearray()
|
| 59 |
+
while len(value) < amount:
|
| 60 |
+
block = os.read(descriptor, amount - len(value))
|
| 61 |
+
if not block:
|
| 62 |
+
break
|
| 63 |
+
value.extend(block)
|
| 64 |
+
return bytes(value)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def validate_gguf_fd(descriptor: int) -> ArtifactEvidence:
|
| 68 |
+
"""Validate the fixed GGUF v2/v3 header without reading a model body."""
|
| 69 |
+
before = _regular(descriptor)
|
| 70 |
+
raw = _read_exact(descriptor, 24)
|
| 71 |
+
if len(raw) != 24 or raw[:4] != b"GGUF":
|
| 72 |
+
raise JsonInputError("candidate is not GGUF")
|
| 73 |
+
version, tensors, metadata = struct.unpack("<IQQ", raw[4:])
|
| 74 |
+
if version not in {2, 3} or not 1 <= tensors <= MAX_GGUF_ITEMS or metadata > MAX_GGUF_ITEMS:
|
| 75 |
+
raise JsonInputError("GGUF fixed header is implausible")
|
| 76 |
+
# Each declared entry needs at least a type/name prefix. This is a lower
|
| 77 |
+
# bound, not a full parser, and rejects maliciously inconsistent headers.
|
| 78 |
+
minimum = 24 + tensors * 12 + metadata * 8
|
| 79 |
+
if minimum > before.st_size or minimum > MAX_ARTIFACT_BYTES:
|
| 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) != (after.st_dev, after.st_ino, after.st_size):
|
| 84 |
+
raise JsonInputError("candidate model artifact changed during validation")
|
| 85 |
+
return ArtifactEvidence(f"gguf-v{version}", "GGUF", before.st_dev, before.st_ino, before.st_size, hashlib.sha256(header).hexdigest())
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def validate_path(path: Path) -> ArtifactEvidence | None:
|
| 89 |
+
"""Return strict GGUF evidence for one locally opened regular file."""
|
| 90 |
+
flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
|
| 91 |
+
try:
|
| 92 |
+
descriptor = os.open(path, flags)
|
| 93 |
+
except OSError:
|
| 94 |
+
return None
|
| 95 |
+
try:
|
| 96 |
+
return validate_gguf_fd(descriptor)
|
| 97 |
+
except (JsonInputError, OSError):
|
| 98 |
+
return None
|
| 99 |
+
finally:
|
| 100 |
+
os.close(descriptor)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def from_process_fds(snapshot: object, *, proc: Path = Path("/proc")) -> tuple[ArtifactEvidence, ...]:
|
| 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
|
| 107 |
+
used only to find a descriptor number; it is never accepted as evidence.
|
| 108 |
+
"""
|
| 109 |
+
identity = snapshot.identity
|
| 110 |
+
entries = tuple(getattr(snapshot, "fd_entries", ()))[:MAX_ARTIFACTS]
|
| 111 |
+
result: list[ArtifactEvidence] = []
|
| 112 |
+
consumed = 0
|
| 113 |
+
for number, _target in entries:
|
| 114 |
+
if not isinstance(number, int) or number < 0:
|
| 115 |
+
continue
|
| 116 |
+
# /proc/<pid>/fd/<n> is necessarily a procfs symlink. We open that
|
| 117 |
+
# exact descriptor target, then validate the opened inode; O_NOFOLLOW
|
| 118 |
+
# would reject every legitimate procfs descriptor.
|
| 119 |
+
flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0)
|
| 120 |
+
try:
|
| 121 |
+
descriptor = os.open(proc / str(identity.pid) / "fd" / str(number), flags)
|
| 122 |
+
except OSError:
|
| 123 |
+
continue
|
| 124 |
+
try:
|
| 125 |
+
evidence = validate_gguf_fd(descriptor)
|
| 126 |
+
header_bytes = min(os.fstat(descriptor).st_size, MAX_ARTIFACT_BYTES)
|
| 127 |
+
if consumed + header_bytes > MAX_TOTAL_BYTES:
|
| 128 |
+
break
|
| 129 |
+
consumed += header_bytes
|
| 130 |
+
if evidence not in result:
|
| 131 |
+
result.append(evidence)
|
| 132 |
+
except (JsonInputError, OSError):
|
| 133 |
+
pass
|
| 134 |
+
finally:
|
| 135 |
+
os.close(descriptor)
|
| 136 |
+
return tuple(result)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def from_snapshot(snapshot: object, *, proc: Path = Path("/proc")) -> tuple[ArtifactEvidence, ...]:
|
| 140 |
+
"""Collect bounded GGUF evidence from open descriptors and mapped files."""
|
| 141 |
+
result = list(from_process_fds(snapshot, proc=proc))
|
| 142 |
+
for raw in tuple(getattr(snapshot, "map_paths", ()))[:MAX_ARTIFACTS]:
|
| 143 |
+
if not isinstance(raw, str) or not raw.startswith("/"):
|
| 144 |
+
continue
|
| 145 |
+
evidence = validate_path(Path(raw))
|
| 146 |
+
if evidence is not None and evidence not in result:
|
| 147 |
+
result.append(evidence)
|
| 148 |
+
return tuple(result[:MAX_ARTIFACTS])
|
src/lumi_eggcracker/detector_catalogue.json
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
{"profiles":[{"all":[{"kind":"exe_basename","values":["llama-cli","llama-server","main"]},{"kind":"argv_model_suffix","values":[".gguf"]}],"id":"llama.cpp"},{"all":[{"kind":"exe_basename","values":["llama-cli","llama-server","main"]},{"kind":"open_model_suffix","values":[".gguf"]}],"id":"llama.cpp-open-model"},{"all":[{"kind":"exe_basename","values":["ollama"]},{"kind":"argv_token","values":["serve","runner"]}],"id":"ollama"},{"all":[{"kind":"exe_basename","values":["python","python3","python3.11","python3.12"]},{"kind":"argv_token","values":["vllm"]}],"id":"vllm-python"},{"all":[{"kind":"exe_basename","values":["vllm"]}],"id":"vllm"},{"all":[{"kind":"exe_basename","values":["text-generation-launcher","text-generation-server"]}],"id":"text-generation-inference"},{"all":[{"kind":"exe_basename","values":["local-ai","localai"]},{"kind":"argv_token","values":["serve","run"]}],"id":"localai"},{"all":[{"kind":"exe_basename","values":["llamafile"]},{"kind":"argv_model_suffix","values":[".gguf"]}],"id":"llamafile"},{"all":[{"kind":"exe_basename","values":["crewai","autogenstudio","langgraph"]}],"id":"agent-cli"},{"all":[{"kind":"exe_basename","values":["python","python3","python3.11","python3.12"]},{"kind":"argv_token","values":["crewai","autogenstudio","langgraph"]}],"id":"agent-python"}],"schema_version":"lumi-eggcracker.detectors.
|
|
|
|
| 1 |
+
{"profiles":[{"all":[{"kind":"exe_basename","values":["llama-cli","llama-server","main"]},{"kind":"argv_model_suffix","values":[".gguf"]}],"id":"llama.cpp","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["llama-cli","llama-server","main"]},{"kind":"open_model_suffix","values":[".gguf"]}],"id":"llama.cpp-open-model","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["ollama"]},{"kind":"argv_token","values":["serve","runner"]}],"id":"ollama","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["python","python3","python3.11","python3.12"]},{"kind":"argv_token","values":["vllm"]}],"id":"vllm-python","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["vllm"]}],"id":"vllm","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["text-generation-launcher","text-generation-server"]}],"id":"text-generation-inference","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["local-ai","localai"]},{"kind":"argv_token","values":["serve","run"]}],"id":"localai","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["llamafile"]},{"kind":"argv_model_suffix","values":[".gguf"]}],"id":"llamafile","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["crewai","autogenstudio","langgraph"]}],"id":"agent-cli","path":"FAST_NAME"},{"all":[{"kind":"exe_basename","values":["python","python3","python3.11","python3.12"]},{"kind":"argv_token","values":["crewai","autogenstudio","langgraph"]}],"id":"agent-python","path":"FAST_NAME"},{"id":"content.gguf-llama","path":"CONTENT","require_all_groups":[{"any":["gguf-v2","gguf-v3"],"group":"MODEL_CONTENT"},{"any":["llama-elf"],"group":"INFERENCE_RUNTIME"}]}],"schema_version":"lumi-eggcracker.detectors.v2"}
|
src/lumi_eggcracker/detectors.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Strict deterministic
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
@@ -11,9 +11,10 @@ from typing import Any, Protocol
|
|
| 11 |
|
| 12 |
from .jsonio import JsonInputError, canonical_bytes
|
| 13 |
|
| 14 |
-
SCHEMA = "lumi-eggcracker.detectors.
|
| 15 |
HEX = re.compile(r"[0-9a-f]{64}\Z")
|
| 16 |
KINDS = {"exe_basename", "argv_token", "argv_model_suffix", "open_model_suffix", "map_basename"}
|
|
|
|
| 17 |
|
| 18 |
|
| 19 |
class Snapshot(Protocol):
|
|
@@ -26,7 +27,9 @@ class Snapshot(Protocol):
|
|
| 26 |
@dataclass(frozen=True)
|
| 27 |
class Profile:
|
| 28 |
identifier: str
|
| 29 |
-
|
|
|
|
|
|
|
| 30 |
|
| 31 |
|
| 32 |
@dataclass(frozen=True)
|
|
@@ -35,6 +38,13 @@ class Catalogue:
|
|
| 35 |
profiles: tuple[Profile, ...]
|
| 36 |
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
def bundled_bytes() -> bytes:
|
| 39 |
return importlib.resources.files("lumi_eggcracker").joinpath("detector_catalogue.json").read_bytes()
|
| 40 |
|
|
@@ -48,6 +58,20 @@ def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
| 48 |
return result
|
| 49 |
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
def load_catalogue(raw: bytes, *, expected_digest: str | None = None) -> Catalogue:
|
| 52 |
digest = hashlib.sha256(raw).hexdigest()
|
| 53 |
if expected_digest is not None and (not HEX.fullmatch(expected_digest) or digest != expected_digest):
|
|
@@ -58,30 +82,46 @@ def load_catalogue(raw: bytes, *, expected_digest: str | None = None) -> Catalog
|
|
| 58 |
raise JsonInputError(f"detector catalogue is invalid: {error}") from error
|
| 59 |
if not isinstance(value, dict) or set(value) != {"profiles", "schema_version"} or value.get("schema_version") != SCHEMA:
|
| 60 |
raise JsonInputError("detector catalogue schema is invalid")
|
| 61 |
-
|
| 62 |
-
if not isinstance(
|
| 63 |
raise JsonInputError("detector catalogue profiles are invalid")
|
| 64 |
-
|
| 65 |
seen: set[str] = set()
|
| 66 |
-
for item in
|
| 67 |
-
if not isinstance(item, dict) or
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
raise JsonInputError("detector profile schema is invalid")
|
| 69 |
-
identifier, predicates = item["id"], item["all"]
|
| 70 |
-
if not isinstance(identifier, str) or not re.fullmatch(r"[a-z][a-z0-9.-]{0,63}", identifier) or identifier in seen:
|
| 71 |
-
raise JsonInputError("detector profile identity is invalid")
|
| 72 |
-
if not isinstance(predicates, list) or not predicates:
|
| 73 |
-
raise JsonInputError("detector profile predicates are invalid")
|
| 74 |
-
clean: list[dict[str, Any]] = []
|
| 75 |
-
for predicate in predicates:
|
| 76 |
-
if not isinstance(predicate, dict) or set(predicate) != {"kind", "values"}:
|
| 77 |
-
raise JsonInputError("detector predicate schema is invalid")
|
| 78 |
-
kind, values = predicate["kind"], predicate["values"]
|
| 79 |
-
if kind not in KINDS or not isinstance(values, list) or not values or not all(isinstance(entry, str) and 1 <= len(entry) <= 128 for entry in values):
|
| 80 |
-
raise JsonInputError("detector predicate is invalid")
|
| 81 |
-
clean.append({"kind": kind, "values": tuple(values)})
|
| 82 |
seen.add(identifier)
|
| 83 |
-
|
| 84 |
-
return Catalogue(digest, tuple(
|
| 85 |
|
| 86 |
|
| 87 |
def load_bundled(*, expected_digest: str | None = None) -> Catalogue:
|
|
@@ -104,19 +144,37 @@ def _matches(snapshot: Snapshot, predicate: dict[str, Any]) -> bool:
|
|
| 104 |
raise JsonInputError("unknown detector predicate")
|
| 105 |
|
| 106 |
|
| 107 |
-
def match(catalogue: Catalogue, snapshot: Snapshot
|
| 108 |
-
"""Return one complete profile match, never
|
|
|
|
| 109 |
for profile in catalogue.profiles:
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
return None
|
| 114 |
|
| 115 |
|
| 116 |
def public_catalogue(catalogue: Catalogue) -> dict[str, Any]:
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
|
| 120 |
def canonical_catalogue_bytes(catalogue: Catalogue) -> bytes:
|
| 121 |
-
"""Small deterministic public representation used only by direct tests."""
|
| 122 |
return canonical_bytes(public_catalogue(catalogue))
|
|
|
|
| 1 |
+
"""Strict deterministic fast-name and content-evidence detector catalogue."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 11 |
|
| 12 |
from .jsonio import JsonInputError, canonical_bytes
|
| 13 |
|
| 14 |
+
SCHEMA = "lumi-eggcracker.detectors.v2"
|
| 15 |
HEX = re.compile(r"[0-9a-f]{64}\Z")
|
| 16 |
KINDS = {"exe_basename", "argv_token", "argv_model_suffix", "open_model_suffix", "map_basename"}
|
| 17 |
+
GROUPS = {"MODEL_CONTENT", "INFERENCE_RUNTIME"}
|
| 18 |
|
| 19 |
|
| 20 |
class Snapshot(Protocol):
|
|
|
|
| 27 |
@dataclass(frozen=True)
|
| 28 |
class Profile:
|
| 29 |
identifier: str
|
| 30 |
+
path: str
|
| 31 |
+
predicates: tuple[dict[str, Any], ...] = ()
|
| 32 |
+
groups: tuple[dict[str, tuple[str, ...]], ...] = ()
|
| 33 |
|
| 34 |
|
| 35 |
@dataclass(frozen=True)
|
|
|
|
| 38 |
profiles: tuple[Profile, ...]
|
| 39 |
|
| 40 |
|
| 41 |
+
@dataclass(frozen=True)
|
| 42 |
+
class DetectionMatch:
|
| 43 |
+
profile: str
|
| 44 |
+
path: str
|
| 45 |
+
evidence: tuple[str, ...]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
def bundled_bytes() -> bytes:
|
| 49 |
return importlib.resources.files("lumi_eggcracker").joinpath("detector_catalogue.json").read_bytes()
|
| 50 |
|
|
|
|
| 58 |
return result
|
| 59 |
|
| 60 |
|
| 61 |
+
def _identifier(value: object) -> str:
|
| 62 |
+
if not isinstance(value, str) or not re.fullmatch(r"[a-z][a-z0-9.-]{0,63}", value):
|
| 63 |
+
raise JsonInputError("detector profile identity is invalid")
|
| 64 |
+
return value
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _values(value: object) -> tuple[str, ...]:
|
| 68 |
+
if not isinstance(value, list) or not value or not all(isinstance(item, str) and 1 <= len(item) <= 128 for item in value):
|
| 69 |
+
raise JsonInputError("detector evidence values are invalid")
|
| 70 |
+
if len(set(value)) != len(value):
|
| 71 |
+
raise JsonInputError("detector evidence values are duplicated")
|
| 72 |
+
return tuple(value)
|
| 73 |
+
|
| 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 (not HEX.fullmatch(expected_digest) or digest != expected_digest):
|
|
|
|
| 82 |
raise JsonInputError(f"detector catalogue is invalid: {error}") from error
|
| 83 |
if not isinstance(value, dict) or set(value) != {"profiles", "schema_version"} or value.get("schema_version") != SCHEMA:
|
| 84 |
raise JsonInputError("detector catalogue schema is invalid")
|
| 85 |
+
raw_profiles = value["profiles"]
|
| 86 |
+
if not isinstance(raw_profiles, list) or not raw_profiles:
|
| 87 |
raise JsonInputError("detector catalogue profiles are invalid")
|
| 88 |
+
profiles: list[Profile] = []
|
| 89 |
seen: set[str] = set()
|
| 90 |
+
for item in raw_profiles:
|
| 91 |
+
if not isinstance(item, dict) or not isinstance(item.get("path"), str):
|
| 92 |
+
raise JsonInputError("detector profile schema is invalid")
|
| 93 |
+
identifier = _identifier(item.get("id"))
|
| 94 |
+
if identifier in seen:
|
| 95 |
+
raise JsonInputError("detector profile identity is duplicated")
|
| 96 |
+
path = item["path"]
|
| 97 |
+
if path == "FAST_NAME" and set(item) == {"all", "id", "path"}:
|
| 98 |
+
predicates: list[dict[str, Any]] = []
|
| 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 not isinstance(predicate, dict) or set(predicate) != {"kind", "values"} or predicate["kind"] not in KINDS:
|
| 103 |
+
raise JsonInputError("detector predicate schema is invalid")
|
| 104 |
+
predicates.append({"kind": predicate["kind"], "values": _values(predicate["values"])})
|
| 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"]
|
| 108 |
+
if not isinstance(raw_groups, list) or len(raw_groups) < 2:
|
| 109 |
+
raise JsonInputError("content profile requires independent evidence groups")
|
| 110 |
+
groups: list[dict[str, tuple[str, ...]]] = []
|
| 111 |
+
present: set[str] = set()
|
| 112 |
+
for group in raw_groups:
|
| 113 |
+
if not isinstance(group, dict) or set(group) != {"any", "group"} or group["group"] not in GROUPS or group["group"] in present:
|
| 114 |
+
raise JsonInputError("content evidence group is invalid")
|
| 115 |
+
present.add(group["group"])
|
| 116 |
+
groups.append({"group": group["group"], "any": _values(group["any"])})
|
| 117 |
+
if present != GROUPS:
|
| 118 |
+
raise JsonInputError("content profile must require model and runtime evidence")
|
| 119 |
+
profile = Profile(identifier, path, groups=tuple(groups))
|
| 120 |
+
else:
|
| 121 |
raise JsonInputError("detector profile schema is invalid")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
seen.add(identifier)
|
| 123 |
+
profiles.append(profile)
|
| 124 |
+
return Catalogue(digest, tuple(profiles))
|
| 125 |
|
| 126 |
|
| 127 |
def load_bundled(*, expected_digest: str | None = None) -> Catalogue:
|
|
|
|
| 144 |
raise JsonInputError("unknown detector predicate")
|
| 145 |
|
| 146 |
|
| 147 |
+
def match(catalogue: Catalogue, snapshot: Snapshot, *, evidence: dict[str, set[str]] | None = None) -> DetectionMatch | None:
|
| 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(predicate["kind"] for predicate in profile.predicates if _matches(snapshot, predicate))
|
| 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(sorted(set(group["any"]).intersection(supplied.get(group["group"], set()))))
|
| 159 |
+
if not values:
|
| 160 |
+
break
|
| 161 |
+
matched_ids.extend(values)
|
| 162 |
+
else:
|
| 163 |
+
return DetectionMatch(profile.identifier, profile.path, tuple(matched_ids))
|
| 164 |
return None
|
| 165 |
|
| 166 |
|
| 167 |
def public_catalogue(catalogue: Catalogue) -> dict[str, Any]:
|
| 168 |
+
profiles: list[dict[str, object]] = []
|
| 169 |
+
for profile in catalogue.profiles:
|
| 170 |
+
value: dict[str, object] = {"id": profile.identifier, "path": profile.path}
|
| 171 |
+
if profile.path == "FAST_NAME":
|
| 172 |
+
value["predicates"] = [item["kind"] for item in profile.predicates]
|
| 173 |
+
else:
|
| 174 |
+
value["evidence_groups"] = [{"group": item["group"], "any": list(item["any"])} for item in profile.groups]
|
| 175 |
+
profiles.append(value)
|
| 176 |
+
return {"digest": catalogue.digest, "profiles": profiles, "schema_version": SCHEMA}
|
| 177 |
|
| 178 |
|
| 179 |
def canonical_catalogue_bytes(catalogue: Catalogue) -> bytes:
|
|
|
|
| 180 |
return canonical_bytes(public_catalogue(catalogue))
|
src/lumi_eggcracker/discovery.py
CHANGED
|
@@ -33,6 +33,8 @@ class ProcessSnapshot:
|
|
| 33 |
cgroups: tuple[str, ...]
|
| 34 |
fd_paths: tuple[str, ...]
|
| 35 |
map_basenames: tuple[str, ...]
|
|
|
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
def _read(path: Path, limit: int = MAX_READ) -> bytes:
|
|
@@ -101,6 +103,20 @@ def _links(directory: Path, *, limit: int) -> tuple[str, ...]:
|
|
| 101 |
return tuple(values)
|
| 102 |
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
def _maps(path: Path) -> tuple[str, ...]:
|
| 105 |
try:
|
| 106 |
raw = _read(path).decode("utf-8", errors="replace")
|
|
@@ -114,6 +130,19 @@ def _maps(path: Path) -> tuple[str, ...]:
|
|
| 114 |
return tuple(values)
|
| 115 |
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
def snapshot(value: ProcessIdentity, *, proc: Path = PROC) -> ProcessSnapshot | None:
|
| 118 |
current = identity(value.pid, proc=proc)
|
| 119 |
if current != value:
|
|
@@ -124,12 +153,14 @@ def snapshot(value: ProcessIdentity, *, proc: Path = PROC) -> ProcessSnapshot |
|
|
| 124 |
command = tuple(item for item in _read(root / "cmdline").decode("utf-8").split("\0") if item)
|
| 125 |
cgroups = tuple(line for line in _read(root / "cgroup", 8192).decode("utf-8").splitlines() if line)
|
| 126 |
uid = _uid(_read(root / "status", 8192).decode("utf-8"))
|
| 127 |
-
|
|
|
|
| 128 |
except (OSError, UnicodeDecodeError, JsonInputError):
|
| 129 |
return None
|
| 130 |
if not command or not exe or len(exe) > 4096:
|
| 131 |
return None
|
| 132 |
-
|
|
|
|
| 133 |
|
| 134 |
|
| 135 |
def scan(*, proc: Path = PROC, exclude: Callable[[ProcessSnapshot], bool] | None = None) -> list[ProcessSnapshot]:
|
|
|
|
| 33 |
cgroups: tuple[str, ...]
|
| 34 |
fd_paths: tuple[str, ...]
|
| 35 |
map_basenames: tuple[str, ...]
|
| 36 |
+
fd_entries: tuple[tuple[int, str], ...] = ()
|
| 37 |
+
map_paths: tuple[str, ...] = ()
|
| 38 |
|
| 39 |
|
| 40 |
def _read(path: Path, limit: int = MAX_READ) -> bytes:
|
|
|
|
| 103 |
return tuple(values)
|
| 104 |
|
| 105 |
|
| 106 |
+
def _fd_entries(directory: Path, *, limit: int) -> tuple[tuple[int, str], ...]:
|
| 107 |
+
values: list[tuple[int, str]] = []
|
| 108 |
+
for item in sorted(directory.iterdir(), key=lambda value: value.name)[:limit]:
|
| 109 |
+
if not item.name.isdigit():
|
| 110 |
+
continue
|
| 111 |
+
try:
|
| 112 |
+
target = os.readlink(item)
|
| 113 |
+
except OSError:
|
| 114 |
+
continue
|
| 115 |
+
if len(target) <= 4096:
|
| 116 |
+
values.append((int(item.name), target.removesuffix(" (deleted)")))
|
| 117 |
+
return tuple(values)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
def _maps(path: Path) -> tuple[str, ...]:
|
| 121 |
try:
|
| 122 |
raw = _read(path).decode("utf-8", errors="replace")
|
|
|
|
| 130 |
return tuple(values)
|
| 131 |
|
| 132 |
|
| 133 |
+
def _map_paths(path: Path) -> tuple[str, ...]:
|
| 134 |
+
try:
|
| 135 |
+
raw = _read(path).decode("utf-8", errors="replace")
|
| 136 |
+
except OSError:
|
| 137 |
+
return ()
|
| 138 |
+
values: list[str] = []
|
| 139 |
+
for line in raw.splitlines()[:MAX_MAPS]:
|
| 140 |
+
parts = line.split(maxsplit=5)
|
| 141 |
+
if len(parts) == 6 and parts[5].startswith("/"):
|
| 142 |
+
values.append(parts[5].removesuffix(" (deleted)"))
|
| 143 |
+
return tuple(values)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
def snapshot(value: ProcessIdentity, *, proc: Path = PROC) -> ProcessSnapshot | None:
|
| 147 |
current = identity(value.pid, proc=proc)
|
| 148 |
if current != value:
|
|
|
|
| 153 |
command = tuple(item for item in _read(root / "cmdline").decode("utf-8").split("\0") if item)
|
| 154 |
cgroups = tuple(line for line in _read(root / "cgroup", 8192).decode("utf-8").splitlines() if line)
|
| 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)
|
| 158 |
except (OSError, UnicodeDecodeError, JsonInputError):
|
| 159 |
return None
|
| 160 |
if not command or not exe or len(exe) > 4096:
|
| 161 |
return None
|
| 162 |
+
maps = _map_paths(root / "maps")
|
| 163 |
+
return ProcessSnapshot(value, uid, exe, Path(exe.removesuffix(" (deleted)")).name, command, cgroups, fd_paths, tuple(Path(item).name for item in maps), fd_entries, maps)
|
| 164 |
|
| 165 |
|
| 166 |
def scan(*, proc: Path = PROC, exclude: Callable[[ProcessSnapshot], bool] | None = None) -> list[ProcessSnapshot]:
|
src/lumi_eggcracker/elfmarkers.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bounded ELF symbol-table markers for supported inference runtimes."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import stat
|
| 7 |
+
import struct
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from .jsonio import JsonInputError
|
| 12 |
+
|
| 13 |
+
MAX_ELF_BYTES = 4 * 1024 * 1024
|
| 14 |
+
MAX_SECTIONS = 1024
|
| 15 |
+
LLAMA_MARKERS = frozenset({"llama_decode", "llama_model_load_from_file", "llama_model_load_from_splits", "ggml_build_forward_expand"})
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass(frozen=True)
|
| 19 |
+
class RuntimeEvidence:
|
| 20 |
+
evidence_id: str
|
| 21 |
+
family: str
|
| 22 |
+
method: str
|
| 23 |
+
markers: tuple[str, ...]
|
| 24 |
+
|
| 25 |
+
def public(self) -> dict[str, object]:
|
| 26 |
+
return {"family": self.family, "method": self.method}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _read(descriptor: int, offset: int, count: int) -> bytes:
|
| 30 |
+
if offset < 0 or count < 0 or offset + count > MAX_ELF_BYTES:
|
| 31 |
+
raise JsonInputError("ELF read exceeds bounded inspection window")
|
| 32 |
+
os.lseek(descriptor, offset, os.SEEK_SET)
|
| 33 |
+
value = os.read(descriptor, count)
|
| 34 |
+
if len(value) != count:
|
| 35 |
+
raise JsonInputError("truncated ELF object")
|
| 36 |
+
return value
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _symbols(descriptor: int, size: int) -> set[str]:
|
| 40 |
+
header = _read(descriptor, 0, 64)
|
| 41 |
+
if header[:4] != b"\x7fELF" or header[4:6] != b"\x02\x01":
|
| 42 |
+
raise JsonInputError("candidate runtime is not little-endian ELF64")
|
| 43 |
+
_type, _machine, _version, _entry, _phoff, section_offset, _flags, header_size, _phent, _phnum, section_size, section_count, _shstr = struct.unpack("<HHIQQQIHHHHHH", header[16:])
|
| 44 |
+
if header_size != 64 or not 1 <= section_count <= MAX_SECTIONS or section_size < 64:
|
| 45 |
+
raise JsonInputError("ELF section table is invalid")
|
| 46 |
+
if section_offset + section_size * section_count > size or section_offset + section_size * section_count > MAX_ELF_BYTES:
|
| 47 |
+
raise JsonInputError("ELF section table exceeds inspection window")
|
| 48 |
+
sections = [_read(descriptor, section_offset + index * section_size, 64) for index in range(section_count)]
|
| 49 |
+
values: set[str] = set()
|
| 50 |
+
for entry in sections:
|
| 51 |
+
_name, kind, _flags, _address, offset, length, link, _info, _align, entry_size = struct.unpack("<IIQQQQIIQQ", entry)
|
| 52 |
+
if kind not in {2, 11} or entry_size != 24 or not length or length > MAX_ELF_BYTES or offset + length > size:
|
| 53 |
+
continue
|
| 54 |
+
if link >= section_count:
|
| 55 |
+
raise JsonInputError("ELF symbol table references invalid string table")
|
| 56 |
+
_n, string_kind, _f, _a, string_offset, string_length, _l, _i, _al, _es = struct.unpack("<IIQQQQIIQQ", sections[link])
|
| 57 |
+
if string_kind != 3 or string_offset + string_length > size or string_length > MAX_ELF_BYTES:
|
| 58 |
+
raise JsonInputError("ELF string table is invalid")
|
| 59 |
+
strings = _read(descriptor, string_offset, string_length)
|
| 60 |
+
symbols = _read(descriptor, offset, length)
|
| 61 |
+
for cursor in range(0, len(symbols), 24):
|
| 62 |
+
name_offset = struct.unpack("<I", symbols[cursor : cursor + 4])[0]
|
| 63 |
+
if name_offset >= len(strings):
|
| 64 |
+
continue
|
| 65 |
+
end = strings.find(b"\0", name_offset)
|
| 66 |
+
if end < 0 or end - name_offset > 256:
|
| 67 |
+
continue
|
| 68 |
+
try:
|
| 69 |
+
values.add(strings[name_offset:end].decode("ascii"))
|
| 70 |
+
except UnicodeDecodeError:
|
| 71 |
+
continue
|
| 72 |
+
return values
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def inspect_path(path: Path) -> RuntimeEvidence | None:
|
| 76 |
+
"""Recognise a llama/GGML ELF by two valid symbol-table markers, not name."""
|
| 77 |
+
flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
|
| 78 |
+
try:
|
| 79 |
+
descriptor = os.open(path, flags)
|
| 80 |
+
except OSError:
|
| 81 |
+
return None
|
| 82 |
+
try:
|
| 83 |
+
before = os.fstat(descriptor)
|
| 84 |
+
if not stat.S_ISREG(before.st_mode) or before.st_size < 64 or before.st_size > (1 << 40):
|
| 85 |
+
return None
|
| 86 |
+
found = tuple(sorted(LLAMA_MARKERS.intersection(_symbols(descriptor, before.st_size))))
|
| 87 |
+
after = os.fstat(descriptor)
|
| 88 |
+
if (before.st_dev, before.st_ino, before.st_size) != (after.st_dev, after.st_ino, after.st_size) or len(found) < 2:
|
| 89 |
+
return None
|
| 90 |
+
return RuntimeEvidence("llama-elf", "llama.cpp/GGML", "ELF_MARKERS", found)
|
| 91 |
+
except (JsonInputError, OSError, struct.error):
|
| 92 |
+
return None
|
| 93 |
+
finally:
|
| 94 |
+
os.close(descriptor)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def from_snapshot(snapshot: object) -> tuple[RuntimeEvidence, ...]:
|
| 98 |
+
"""Inspect executable and mapped regular files; their names are ignored."""
|
| 99 |
+
candidates = [getattr(snapshot, "exe_path", ""), *getattr(snapshot, "map_paths", ())]
|
| 100 |
+
result: list[RuntimeEvidence] = []
|
| 101 |
+
for raw in candidates[:513]:
|
| 102 |
+
evidence = inspect_path(Path(raw)) if isinstance(raw, str) and raw.startswith("/") else None
|
| 103 |
+
if evidence is not None and evidence not in result:
|
| 104 |
+
result.append(evidence)
|
| 105 |
+
return tuple(result)
|
src/lumi_eggcracker/observation.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Short-lived, PID/start-time-bound content observations."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import time
|
| 6 |
+
from collections.abc import Hashable
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
|
| 9 |
+
MAX_OBSERVATIONS = 4096
|
| 10 |
+
MAX_AGE_NS = 10_000_000_000
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass(frozen=True)
|
| 14 |
+
class Observation:
|
| 15 |
+
evidence: frozenset[str]
|
| 16 |
+
first_seen_ns: int
|
| 17 |
+
last_seen_ns: int
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ObservationStore:
|
| 21 |
+
def __init__(self) -> None:
|
| 22 |
+
self._values: dict[Hashable, Observation] = {}
|
| 23 |
+
|
| 24 |
+
def observe(self, identity: Hashable, evidence: set[str], *, now_ns: int | None = None) -> Observation:
|
| 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(frozenset(evidence) | (previous.evidence if previous else frozenset()), previous.first_seen_ns if previous else now, now)
|
| 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)
|
| 32 |
+
if oldest != identity:
|
| 33 |
+
self._values.pop(oldest, None)
|
| 34 |
+
return value
|
| 35 |
+
|
| 36 |
+
def expire(self, *, now_ns: int | None = None) -> None:
|
| 37 |
+
now = time.monotonic_ns() if now_ns is None else now_ns
|
| 38 |
+
for key, value in tuple(self._values.items()):
|
| 39 |
+
if now - value.last_seen_ns > MAX_AGE_NS:
|
| 40 |
+
self._values.pop(key, None)
|
src/lumi_eggcracker/supervisor.py
CHANGED
|
@@ -26,6 +26,8 @@ from .approvals import approved, revoke
|
|
| 26 |
from .approvals import create as create_approval
|
| 27 |
from .approvals import load_all as load_approvals
|
| 28 |
from .approvals import public as public_approval
|
|
|
|
|
|
|
| 29 |
from .containment import (
|
| 30 |
capture_identity,
|
| 31 |
events_from_fd,
|
|
@@ -33,9 +35,12 @@ from .containment import (
|
|
| 33 |
validate_identity,
|
| 34 |
verify_empty,
|
| 35 |
)
|
| 36 |
-
from .detectors import Catalogue, load_catalogue, match, public_catalogue
|
| 37 |
from .discovery import ProcessIdentity, ProcessSnapshot, executable_digest, scan
|
|
|
|
|
|
|
| 38 |
from .jsonio import JsonInputError, load_regular_json
|
|
|
|
| 39 |
from .records import (
|
| 40 |
ACTIVE_STATES,
|
| 41 |
RUN_ID,
|
|
@@ -138,6 +143,7 @@ class Supervisor:
|
|
| 138 |
self.discovery_active: set[ProcessIdentity] = set()
|
| 139 |
self.discovery_thread: threading.Thread | None = None
|
| 140 |
self.digest_cache: dict[tuple[int, int, int, int], str] = {}
|
|
|
|
| 141 |
|
| 142 |
@property
|
| 143 |
def operator_uid(self) -> int:
|
|
@@ -277,8 +283,13 @@ class Supervisor:
|
|
| 277 |
for path in records[DETECTION_LIMIT:]:
|
| 278 |
path.unlink(missing_ok=True)
|
| 279 |
|
| 280 |
-
def _detection_receipt(self, *, event_id: str, snapshot: ProcessSnapshot,
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
if result is None:
|
| 283 |
value["result"] = "CONTAINMENT_FAILED"
|
| 284 |
value["error"] = (error or "containment failed")[:160]
|
|
@@ -286,18 +297,18 @@ class Supervisor:
|
|
| 286 |
value.update({"result": "TERMINATED", "capture": {"captured_processes": len(result.captured), "fixed_point_scans": result.fixed_point_scans, "quarantine_cgroup": str(result.identity.path), "quarantine_device": result.identity.device, "quarantine_inode": result.identity.inode}, "containment": {"empty_verified_monotonic_ns": result.empty_ns, "first_stop_monotonic_ns": result.first_stop_ns, "kill_write_completed_monotonic_ns": result.kill_complete_ns, "kill_write_started_monotonic_ns": result.kill_started_ns, "primitive": "pidfd-stop+cgroup.kill", "root_populated": result.proof.root_populated, "surviving_pids": result.proof.surviving_pids, "trigger_to_empty_ms": (result.empty_ns - result.first_stop_ns) / 1_000_000}, "trigger": {"kind": "UNAPPROVED_AI_MATCH", "observed_monotonic_ns": result.first_stop_ns}})
|
| 287 |
return value
|
| 288 |
|
| 289 |
-
def _enforce_discovery(self, snapshot: ProcessSnapshot,
|
| 290 |
try:
|
| 291 |
if self.quarantine_root is None:
|
| 292 |
raise JsonInputError("quarantine root is unavailable")
|
| 293 |
self.operations.append("pidfd.stop")
|
| 294 |
result = contain(snapshot.identity, self.quarantine_root, event_id)
|
| 295 |
self.operations.append("cgroup.kill")
|
| 296 |
-
receipt = self._detection_receipt(event_id=event_id, snapshot=snapshot,
|
| 297 |
receipt["receipt_written_utc"] = dt.datetime.now(dt.UTC).isoformat().replace("+00:00", "Z")
|
| 298 |
self._store_detection(receipt)
|
| 299 |
except (JsonInputError, OSError, RuntimeError, ProcessLookupError) as error:
|
| 300 |
-
receipt = self._detection_receipt(event_id=event_id, snapshot=snapshot,
|
| 301 |
receipt["receipt_written_utc"] = dt.datetime.now(dt.UTC).isoformat().replace("+00:00", "Z")
|
| 302 |
try:
|
| 303 |
self._store_detection(receipt)
|
|
@@ -313,8 +324,20 @@ class Supervisor:
|
|
| 313 |
except JsonInputError:
|
| 314 |
approvals = [] # A corrupt approval never authorizes a matching workload.
|
| 315 |
for snapshot in scan(exclude=lambda item: item.identity.pid == os.getpid() or self._managed(item)):
|
| 316 |
-
|
| 317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
continue
|
| 319 |
try:
|
| 320 |
executable_sha256 = self._cached_executable_digest(snapshot)
|
|
@@ -326,12 +349,11 @@ class Supervisor:
|
|
| 326 |
if snapshot.identity in self.discovery_active:
|
| 327 |
continue
|
| 328 |
self.discovery_active.add(snapshot.identity)
|
| 329 |
-
profile, predicates = result
|
| 330 |
event_id = os.urandom(12).hex()
|
| 331 |
if synchronous:
|
| 332 |
-
self._enforce_discovery(snapshot,
|
| 333 |
else:
|
| 334 |
-
threading.Thread(target=self._enforce_discovery, args=(snapshot,
|
| 335 |
|
| 336 |
def _discovery_loop(self) -> None:
|
| 337 |
while not self.stop_event.is_set():
|
|
|
|
| 26 |
from .approvals import create as create_approval
|
| 27 |
from .approvals import load_all as load_approvals
|
| 28 |
from .approvals import public as public_approval
|
| 29 |
+
from .artifacts import ArtifactEvidence
|
| 30 |
+
from .artifacts import from_snapshot as artifacts_from_snapshot
|
| 31 |
from .containment import (
|
| 32 |
capture_identity,
|
| 33 |
events_from_fd,
|
|
|
|
| 35 |
validate_identity,
|
| 36 |
verify_empty,
|
| 37 |
)
|
| 38 |
+
from .detectors import Catalogue, DetectionMatch, load_catalogue, match, public_catalogue
|
| 39 |
from .discovery import ProcessIdentity, ProcessSnapshot, executable_digest, scan
|
| 40 |
+
from .elfmarkers import RuntimeEvidence
|
| 41 |
+
from .elfmarkers import from_snapshot as runtime_from_snapshot
|
| 42 |
from .jsonio import JsonInputError, load_regular_json
|
| 43 |
+
from .observation import ObservationStore
|
| 44 |
from .records import (
|
| 45 |
ACTIVE_STATES,
|
| 46 |
RUN_ID,
|
|
|
|
| 143 |
self.discovery_active: set[ProcessIdentity] = set()
|
| 144 |
self.discovery_thread: threading.Thread | None = None
|
| 145 |
self.digest_cache: dict[tuple[int, int, int, int], str] = {}
|
| 146 |
+
self.observations = ObservationStore()
|
| 147 |
|
| 148 |
@property
|
| 149 |
def operator_uid(self) -> int:
|
|
|
|
| 283 |
for path in records[DETECTION_LIMIT:]:
|
| 284 |
path.unlink(missing_ok=True)
|
| 285 |
|
| 286 |
+
def _detection_receipt(self, *, event_id: str, snapshot: ProcessSnapshot, detected: DetectionMatch, content: tuple[ArtifactEvidence, ...], runtimes: tuple[RuntimeEvidence, ...], first_seen_ns: int, executable_sha256: str, result: AdoptionResult | None, error: str | None) -> dict[str, Any]:
|
| 287 |
+
detector: dict[str, Any] = {"catalogue_schema": "lumi-eggcracker.detectors.v2", "detection_path": detected.path, "matched_evidence": list(detected.evidence), "matched_predicates": list(detected.evidence), "profile": detected.profile}
|
| 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"] = {"first_seen_monotonic_ns": first_seen_ns, "qualified_monotonic_ns": time.monotonic_ns()}
|
| 292 |
+
value: dict[str, Any] = {"catalogue_sha256": self.catalogue.digest, "detector": detector, "event_id": event_id, "executable": {"basename": snapshot.exe_basename, "sha256": executable_sha256}, "observed": {"argv_count": len(snapshot.argv), "argv_sha256": hashlib.sha256("\0".join(snapshot.argv).encode("utf-8")).hexdigest(), "pid": snapshot.identity.pid, "start_time": snapshot.identity.start_time, "uid": snapshot.uid}, "receipt_written_utc": None, "schema_version": "lumi-eggcracker.detection-receipt.v2", "source_commit": self.policy["source_commit"], "trigger": {"kind": "UNAPPROVED_AI_MATCH"}, "version": __version__}
|
| 293 |
if result is None:
|
| 294 |
value["result"] = "CONTAINMENT_FAILED"
|
| 295 |
value["error"] = (error or "containment failed")[:160]
|
|
|
|
| 297 |
value.update({"result": "TERMINATED", "capture": {"captured_processes": len(result.captured), "fixed_point_scans": result.fixed_point_scans, "quarantine_cgroup": str(result.identity.path), "quarantine_device": result.identity.device, "quarantine_inode": result.identity.inode}, "containment": {"empty_verified_monotonic_ns": result.empty_ns, "first_stop_monotonic_ns": result.first_stop_ns, "kill_write_completed_monotonic_ns": result.kill_complete_ns, "kill_write_started_monotonic_ns": result.kill_started_ns, "primitive": "pidfd-stop+cgroup.kill", "root_populated": result.proof.root_populated, "surviving_pids": result.proof.surviving_pids, "trigger_to_empty_ms": (result.empty_ns - result.first_stop_ns) / 1_000_000}, "trigger": {"kind": "UNAPPROVED_AI_MATCH", "observed_monotonic_ns": result.first_stop_ns}})
|
| 298 |
return value
|
| 299 |
|
| 300 |
+
def _enforce_discovery(self, snapshot: ProcessSnapshot, detected: DetectionMatch, content: tuple[ArtifactEvidence, ...], runtimes: tuple[RuntimeEvidence, ...], first_seen_ns: int, executable_sha256: str, event_id: str) -> None:
|
| 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(event_id=event_id, snapshot=snapshot, detected=detected, content=content, runtimes=runtimes, first_seen_ns=first_seen_ns, executable_sha256=executable_sha256, result=result, error=None)
|
| 308 |
receipt["receipt_written_utc"] = dt.datetime.now(dt.UTC).isoformat().replace("+00:00", "Z")
|
| 309 |
self._store_detection(receipt)
|
| 310 |
except (JsonInputError, OSError, RuntimeError, ProcessLookupError) as error:
|
| 311 |
+
receipt = self._detection_receipt(event_id=event_id, snapshot=snapshot, detected=detected, content=content, runtimes=runtimes, first_seen_ns=first_seen_ns, executable_sha256=executable_sha256, result=None, error=str(error))
|
| 312 |
receipt["receipt_written_utc"] = dt.datetime.now(dt.UTC).isoformat().replace("+00:00", "Z")
|
| 313 |
try:
|
| 314 |
self._store_detection(receipt)
|
|
|
|
| 324 |
except JsonInputError:
|
| 325 |
approvals = [] # A corrupt approval never authorizes a matching workload.
|
| 326 |
for snapshot in scan(exclude=lambda item: item.identity.pid == os.getpid() or self._managed(item)):
|
| 327 |
+
detected = match(self.catalogue, snapshot)
|
| 328 |
+
content: tuple[ArtifactEvidence, ...] = ()
|
| 329 |
+
runtimes: tuple[RuntimeEvidence, ...] = ()
|
| 330 |
+
first_seen_ns = time.monotonic_ns()
|
| 331 |
+
if detected is None:
|
| 332 |
+
content = artifacts_from_snapshot(snapshot)
|
| 333 |
+
runtimes = runtime_from_snapshot(snapshot)
|
| 334 |
+
supplied = {"MODEL_CONTENT": {item.evidence_id for item in content}, "INFERENCE_RUNTIME": {item.evidence_id for item in runtimes}}
|
| 335 |
+
observation = self.observations.observe(snapshot.identity, set().union(*supplied.values()))
|
| 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)
|
|
|
|
| 349 |
if snapshot.identity in self.discovery_active:
|
| 350 |
continue
|
| 351 |
self.discovery_active.add(snapshot.identity)
|
|
|
|
| 352 |
event_id = os.urandom(12).hex()
|
| 353 |
if synchronous:
|
| 354 |
+
self._enforce_discovery(snapshot, detected, content, runtimes, first_seen_ns, executable_sha256, event_id)
|
| 355 |
else:
|
| 356 |
+
threading.Thread(target=self._enforce_discovery, args=(snapshot, detected, content, runtimes, first_seen_ns, executable_sha256, event_id), daemon=True).start()
|
| 357 |
|
| 358 |
def _discovery_loop(self) -> None:
|
| 359 |
while not self.stop_event.is_set():
|
tests/test_artifacts.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import struct
|
| 5 |
+
import tempfile
|
| 6 |
+
import unittest
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from lumi_eggcracker.artifacts import validate_path
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def gguf(*, version: int = 3, tensors: int = 1, metadata: int = 0, padding: int = 64) -> bytes:
|
| 13 |
+
return b"GGUF" + struct.pack("<IQQ", version, tensors, metadata) + b"\0" * padding
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ArtifactTests(unittest.TestCase):
|
| 17 |
+
def test_valid_gguf_content_does_not_depend_on_filename(self) -> None:
|
| 18 |
+
with tempfile.TemporaryDirectory() as raw:
|
| 19 |
+
path = Path(raw) / "opaque-input"
|
| 20 |
+
path.write_bytes(gguf())
|
| 21 |
+
evidence = validate_path(path)
|
| 22 |
+
self.assertIsNotNone(evidence)
|
| 23 |
+
assert evidence is not None
|
| 24 |
+
self.assertEqual("gguf-v3", evidence.evidence_id)
|
| 25 |
+
self.assertNotIn(path.name, evidence.header_sha256)
|
| 26 |
+
|
| 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((b"NOPE" + gguf()[4:], gguf(version=1), gguf(tensors=1_000_000, padding=1))):
|
| 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); target = root / "target"; link = root / "link"
|
| 38 |
+
target.write_bytes(gguf())
|
| 39 |
+
try:
|
| 40 |
+
os.symlink(target, link)
|
| 41 |
+
except OSError as error:
|
| 42 |
+
self.skipTest(f"symlinks unavailable: {error}")
|
| 43 |
+
self.assertIsNone(validate_path(link))
|
tests/test_cli.py
CHANGED
|
@@ -13,7 +13,7 @@ class CliTests(unittest.TestCase):
|
|
| 13 |
output = io.StringIO()
|
| 14 |
with redirect_stdout(output):
|
| 15 |
self.assertEqual(0, main(["version"]))
|
| 16 |
-
self.assertEqual("0.
|
| 17 |
|
| 18 |
def test_public_help_has_only_supported_commands(self) -> None:
|
| 19 |
from lumi_eggcracker.cli import _parser
|
|
|
|
| 13 |
output = io.StringIO()
|
| 14 |
with redirect_stdout(output):
|
| 15 |
self.assertEqual(0, main(["version"]))
|
| 16 |
+
self.assertEqual("0.3.0", output.getvalue().strip())
|
| 17 |
|
| 18 |
def test_public_help_has_only_supported_commands(self) -> None:
|
| 19 |
from lumi_eggcracker.cli import _parser
|
tests/test_detectors.py
CHANGED
|
@@ -3,7 +3,7 @@ from __future__ import annotations
|
|
| 3 |
import unittest
|
| 4 |
from dataclasses import dataclass
|
| 5 |
|
| 6 |
-
from lumi_eggcracker.detectors import load_bundled, load_catalogue, match
|
| 7 |
from lumi_eggcracker.jsonio import JsonInputError
|
| 8 |
|
| 9 |
|
|
@@ -16,23 +16,32 @@ class Sample:
|
|
| 16 |
|
| 17 |
|
| 18 |
class DetectorTests(unittest.TestCase):
|
| 19 |
-
def
|
| 20 |
catalogue = load_bundled()
|
| 21 |
self.assertIsNone(match(catalogue, Sample("llama-cli", ("/usr/bin/llama-cli", "--help"))))
|
| 22 |
value = match(catalogue, Sample("llama-cli", ("/usr/bin/llama-cli", "-m", "/models/tiny.gguf")))
|
| 23 |
-
self.assertEqual(("llama.cpp", ("exe_basename", "argv_model_suffix")), value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
def test_generic_language_runtime_is_not_a_match(self) -> None:
|
| 26 |
catalogue = load_bundled()
|
| 27 |
self.assertIsNone(match(catalogue, Sample("python3", ("/usr/bin/python3", "worker.py", "--model", "cat"))))
|
| 28 |
self.assertIsNone(match(catalogue, Sample("node", ("node", "agent.js"))))
|
| 29 |
|
| 30 |
-
def
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
| 34 |
|
| 35 |
def test_catalogue_digest_is_exact(self) -> None:
|
| 36 |
-
raw = b'{"schema_version":"lumi-eggcracker.detectors.
|
| 37 |
with self.assertRaises(JsonInputError):
|
| 38 |
load_catalogue(raw, expected_digest="0" * 64)
|
|
|
|
| 3 |
import unittest
|
| 4 |
from dataclasses import dataclass
|
| 5 |
|
| 6 |
+
from lumi_eggcracker.detectors import DetectionMatch, load_bundled, load_catalogue, match
|
| 7 |
from lumi_eggcracker.jsonio import JsonInputError
|
| 8 |
|
| 9 |
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
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(catalogue, Sample("llama-cli", ("/usr/bin/llama-cli", "-m", "/models/tiny.gguf")))
|
| 23 |
+
self.assertEqual(DetectionMatch("llama.cpp", "FAST_NAME", ("exe_basename", "argv_model_suffix")), value)
|
| 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(DetectionMatch("content.gguf-llama", "CONTENT", ("gguf-v3", "llama-elf")), match(catalogue, sample, evidence={"MODEL_CONTENT": {"gguf-v3"}, "INFERENCE_RUNTIME": {"llama-elf"}}))
|
| 31 |
|
| 32 |
def test_generic_language_runtime_is_not_a_match(self) -> None:
|
| 33 |
catalogue = load_bundled()
|
| 34 |
self.assertIsNone(match(catalogue, Sample("python3", ("/usr/bin/python3", "worker.py", "--model", "cat"))))
|
| 35 |
self.assertIsNone(match(catalogue, Sample("node", ("node", "agent.js"))))
|
| 36 |
|
| 37 |
+
def test_catalogue_rejects_unknown_predicate_and_incomplete_content_group(self) -> None:
|
| 38 |
+
unknown = b'{"schema_version":"lumi-eggcracker.detectors.v2","profiles":[{"id":"bad","path":"FAST_NAME","all":[{"kind":"unknown","values":["x"]}]}]}'
|
| 39 |
+
incomplete = b'{"schema_version":"lumi-eggcracker.detectors.v2","profiles":[{"id":"bad","path":"CONTENT","require_all_groups":[{"group":"MODEL_CONTENT","any":["gguf-v3"]}]}]}'
|
| 40 |
+
for raw in (unknown, incomplete):
|
| 41 |
+
with self.assertRaises(JsonInputError):
|
| 42 |
+
load_catalogue(raw)
|
| 43 |
|
| 44 |
def test_catalogue_digest_is_exact(self) -> None:
|
| 45 |
+
raw = b'{"schema_version":"lumi-eggcracker.detectors.v2","profiles":[{"id":"one","path":"FAST_NAME","all":[{"kind":"exe_basename","values":["one"]}]}]}'
|
| 46 |
with self.assertRaises(JsonInputError):
|
| 47 |
load_catalogue(raw, expected_digest="0" * 64)
|
tests/test_elfmarkers.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import struct
|
| 4 |
+
import tempfile
|
| 5 |
+
import unittest
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from lumi_eggcracker.elfmarkers import inspect_path
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def elf(*, markers: tuple[str, ...], append_decoys: bool = False) -> bytes:
|
| 12 |
+
strings = b"\0" + b"".join(item.encode() + b"\0" for item in markers)
|
| 13 |
+
names: list[int] = []
|
| 14 |
+
cursor = 1
|
| 15 |
+
for item in markers:
|
| 16 |
+
names.append(cursor); cursor += len(item) + 1
|
| 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("<IIQQQQIIQQ", 0, 2, 0, 0, 512, len(markers) * 24, 1, 0, 8, 24)
|
| 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("<IBBHQQ", name, 0, 0, 1, 0, 0)
|
| 25 |
+
if append_decoys:
|
| 26 |
+
body.extend(b"llama_decode\0llama_model_load_from_file\0")
|
| 27 |
+
return bytes(body)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ElfMarkerTests(unittest.TestCase):
|
| 31 |
+
def test_two_valid_symbol_markers_qualify_regardless_of_filename(self) -> None:
|
| 32 |
+
with tempfile.TemporaryDirectory() as raw:
|
| 33 |
+
path = Path(raw) / "unrelated-name"
|
| 34 |
+
path.write_bytes(elf(markers=("llama_decode", "llama_model_load_from_file")))
|
| 35 |
+
evidence = inspect_path(path)
|
| 36 |
+
self.assertIsNotNone(evidence)
|
| 37 |
+
assert evidence is not None
|
| 38 |
+
self.assertEqual("llama-elf", evidence.evidence_id)
|
| 39 |
+
self.assertEqual("ELF_MARKERS", evidence.method)
|
| 40 |
+
|
| 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((elf(markers=("llama_decode",)), elf(markers=(), append_decoys=True), b"not an elf")):
|
| 45 |
+
path = root / str(index); path.write_bytes(body)
|
| 46 |
+
self.assertIsNone(inspect_path(path))
|
tests/test_observation.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
|
| 5 |
+
from lumi_eggcracker.observation import ObservationStore
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ObservationTests(unittest.TestCase):
|
| 9 |
+
def test_observation_expires_and_pid_reuse_identity_is_not_joined(self) -> None:
|
| 10 |
+
store = ObservationStore()
|
| 11 |
+
first = store.observe((42, 100), {"gguf-v3"}, now_ns=1)
|
| 12 |
+
second = store.observe((42, 101), {"llama-elf"}, now_ns=2)
|
| 13 |
+
self.assertEqual(frozenset({"gguf-v3"}), first.evidence)
|
| 14 |
+
self.assertEqual(frozenset({"llama-elf"}), second.evidence)
|
| 15 |
+
store.expire(now_ns=11_000_000_003)
|
| 16 |
+
fresh = store.observe((42, 101), {"llama-elf"}, now_ns=11_000_000_004)
|
| 17 |
+
self.assertEqual(frozenset({"llama-elf"}), fresh.evidence)
|