feat(poc-a): gate-a dynamic elf proof of concept (#13)
## Summary PoC-A proved that dynamically loaded ELF plugins are workable on ESP32-S3: plugins ship as signed MPB packages, are parsed by a strict single-type parser shared between host and target, and execute from PSRAM+IRAM within a measured admission budget. A 1000-cycle load/unload soak passed 18/18 trend gates with stable heaps, the capacity ladder settled at 8 coexisting plugin instances with a 3356B per-instance budget, and the fail-closed corpus executed zero attacker-controlled bytes across 14 rejection classes. Scheduler semantics (strand FIFO ordering, completion-cancel CAS, quiesce-as-noop ABI) were validated on both host (TSan suite) and target. **Gate-A verdict: PASS** — ADR-0002 moves to **Accepted** with the capacity value 8 and global-sum admission rule as PoC-derived proposals. ## Changes by area Grouped from `git log main..HEAD --oneline` (18 commits): - **Vendored loader + patches**: `4bb53f2` vendor elf_loader 1.3.3 + harness scaffold; `2f67b4f` plugin_iram loader patch with budget consistency (p1-p5 patch series in `PATCHES.md`). - **MPB toolchain**: `4793cc2` deterministic MPB manifest builder with test signing; `408df44` strict single-type MPB parser shared host/target; `796f9d2` host MPB corpus + policy CI lane. - **Plugin pipeline + probes**: `21d2842` plugin pipeline and first PSRAM execution on target; `cab9664` relocation/import allowlist matrix with probes; `c5d6c6c` C++ feature rejection matrix. - **Harness commands**: `e0e7159` generation coexistence with measured admission budget; `2a37556` thousand-cycle lifecycle soak with heap trend gate; `093a72b` on-target scheduler semantics validation (+ `eea3876` clang-format-18 sweep); `a302151` capacity ladder with signed budget; `f34dc72` fail-closed corpus with execution sentinel. - **Host prototypes**: `6198bca` strand FIFO prototype with TSan suite; `1c3ad59` completion-cancel CAS and cleanup semantics. - **Evidence + ADR/docs**: `887d0f7` Gate-A manifest and report; `1c29e8a` ADR-0002 outcome + frozen PoC values. ## QA evidence - `poc/evidence/poc-a-20260901/manifest.json` — 67-artifact hash index, every sha256 recomputed at assembly. - `poc/evidence/poc-a-20260901/GATE-A-REPORT.md` — full nine-item development-plan §4 mapping; TEST-003 10/10 clauses. - 14 verbatim per-task transcripts (`task-1` … `task-15-*.log`) + fresh build artifacts (`build/frame_poc_a.map`, size components). - Frozen in-repo references: `ALLOWLIST.md`, `REJECT-MATRIX.md`, `ADMISSION-BUDGET.md`, `soak_samples_1000.csv`, fc corpus (33 committed `.mpb` containers). - F1-F4 final-wave verdicts: **APPROVE**. - Key numbers: soak **18/18** trend gates over 1000 cycles; capacity **8/8** instances, **3356B** per-instance; fc corpus **14 rejection classes, zero attacker bytes executed**; **4 upstream loader defects found and patched** (p1-p5). ## Requirement IDs (GOV-006) ADR-0002; TEST-002, TEST-003; PLUG-001, PLUG-004, PLUG-008, PLUG-009; MEM-001, MEM-003, MEM-007, MEM-008; LIFE-001, LIFE-002, LIFE-005, LIFE-007; SEC-002, SEC-003, SEC-004, SEC-005; GH-003; GOV-004, GOV-005. ## Risks / known limitations From `GATE-A-REPORT.md` §(f) plus the trade-off table: 1. **Capacity descent path 7-5 unexercised** — rung 8 passed first attempt; rungs 7/6/5 and retry-once logic never ran on hardware (untested against real OOM). 2. **No Wi-Fi in the harness (MEM-001 caveat)** — all PSRAM/IRAM budget numbers are radio-off harness-class; product admission budgets must be re-measured with the network stack active. 3. **On-target scheduler vectors are a subset of the host suite** (256-node pool / 2e4 storm posts vs host 31000 / 1e5); consistency declaration covers only the vectors actually run. 4. **Quiesce is a no-op by ABI semantics** — plugin ABI 1.2 has no quiesce slot; NULL entry is defined as trivial success; real quiesce coordination is later-gate work. 5. **MEMPROT=n trade-off** — `CONFIG_ESP_SYSTEM_MEMPROT=n` is required for the IDF exec heap (`MALLOC_CAP_EXEC`) that `.plugin_iram` needs; software-only PMP config, no eFuse burned (documented in `PATCHES.md` p5); production must re-decide security vs plugin IRAM. 6. **Owner sign-off PENDING** — Gate-A PASS is the PoC team's verdict; formal acceptance of ADR-0002 awaits the owner. ## Not in scope - Product components (GOV-004) — this PR is PoC evidence only; no product code paths change. - **Merge is the owner's call** — do not merge without owner sign-off on ADR-0002. --------- Co-authored-by: ania-lain <[email protected]>
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
"""T8 admission corpus builder: over-declared max_memory_bytes negative.
|
||||
|
||||
Starting from the gate-approved baseline.elf (check_plugin_elf.cmake ran on
|
||||
it), builds the negative container neg_maxmem: the manifest declares
|
||||
max_memory_bytes = 614400 (600 KiB), past the 512 KiB hard maximum of
|
||||
MEM-003/PLUG-004 admission. Manifest.encode() would refuse the value
|
||||
(cross-field validation rejects > MAX_PLUGIN_MEMORY_BYTES), so the manifest
|
||||
TLVs are hand-packed here and the container goes through assemble_mpb (the
|
||||
hostile_signed pattern proven in T5/T6/T7). The signature is valid: the
|
||||
on-device rejection must come from the poca admission check
|
||||
(max_memory_bytes > 512 KiB hard max), before esp_elf_init and before any
|
||||
plugin byte executes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[5]
|
||||
sys.path.insert(0, str(REPO_ROOT / "tools"))
|
||||
|
||||
from frame_tools.manifest_builder import ( # noqa: E402
|
||||
PAYLOAD_TYPE_ELF,
|
||||
PAYLOAD_ENTRY_SIZE,
|
||||
SIGNATURE_RECORD_SIZE,
|
||||
TLV_FLAG_REQUIRED,
|
||||
TLV_HEADER_FMT,
|
||||
Payload,
|
||||
assemble_mpb,
|
||||
derive_key_id,
|
||||
load_private_key,
|
||||
sign_digest_deterministic,
|
||||
)
|
||||
|
||||
DECLARED_MAX_MEMORY = 600 * 1024
|
||||
HARD_MAX = 512 * 1024
|
||||
|
||||
|
||||
def _tlv(field_id: int, flags: int, value: bytes) -> bytes:
|
||||
return struct.pack(TLV_HEADER_FMT, field_id, flags, len(value)) + value
|
||||
|
||||
|
||||
def hostile_manifest_bytes() -> bytes:
|
||||
"""Hand-packed manifest TLVs (name=1, version=2, max_memory_bytes=4)."""
|
||||
return b"".join(
|
||||
[
|
||||
_tlv(1, TLV_FLAG_REQUIRED, b"baseline"),
|
||||
_tlv(2, TLV_FLAG_REQUIRED, b"1.0.0"),
|
||||
_tlv(4, 0, struct.pack("<I", DECLARED_MAX_MEMORY)),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def hostile_signed(manifest_bytes: bytes, elf: bytes, key) -> bytes:
|
||||
"""Sign over arbitrary manifest bytes (the T2/T3 tests/test_manifest_builder
|
||||
hostile_signed pattern): assemble_mpb would run its post-sign semantic
|
||||
self-verify, which refuses max_memory_bytes > 512 KiB — exactly the rule
|
||||
this fixture violates — so the digest is signed directly and the IEEE
|
||||
P1363 r||s record is spliced in at signature_offset."""
|
||||
container = assemble_mpb(
|
||||
manifest_bytes=manifest_bytes,
|
||||
payloads=[Payload(kind=PAYLOAD_TYPE_ELF, data=elf)],
|
||||
key_id=derive_key_id(key.public_key()),
|
||||
flags=0,
|
||||
)
|
||||
table_end = struct.unpack_from("<I", container, 52)[0] + PAYLOAD_ENTRY_SIZE
|
||||
digest = hashlib.sha256(container[:table_end]).digest()
|
||||
signature = sign_digest_deterministic(key, digest)
|
||||
offset = struct.unpack_from("<I", container, 60)[0]
|
||||
container = bytearray(container)
|
||||
container[offset + 8 : offset + SIGNATURE_RECORD_SIZE] = signature
|
||||
return bytes(container)
|
||||
|
||||
|
||||
def write_meta(out_dir: Path, name: str, container: bytes) -> None:
|
||||
digest = hashlib.sha256(container).hexdigest()
|
||||
upper = name.upper()
|
||||
header = (
|
||||
f"/* Generated by poc/apps/poc_a/plugins/coexist/build_maxmem_corpus.py - do not edit. */\n"
|
||||
f"#define POCA_{upper}_MPB_SIZE {len(container)}u\n"
|
||||
f'#define POCA_{upper}_MPB_SHA256 "{digest}"\n'
|
||||
f'#define POCA_{upper}_NAME "baseline"\n'
|
||||
f'#define POCA_{upper}_VERSION "1.0.0"\n'
|
||||
f'#define POCA_{upper}_ENTRY "frame_plugin_entry"\n'
|
||||
)
|
||||
(out_dir / "generated" / f"poca_{name}_meta.h").write_text(header)
|
||||
print(f"[maxmem-corpus] {name}.mpb size={len(container)} sha256={digest}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--baseline-elf", required=True)
|
||||
parser.add_argument("--key", required=True)
|
||||
parser.add_argument("--out-dir", required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
if DECLARED_MAX_MEMORY <= HARD_MAX:
|
||||
raise SystemExit("[maxmem-corpus] fixture bug: declared value must exceed the hard max")
|
||||
|
||||
out_dir = Path(args.out_dir)
|
||||
(out_dir / "generated").mkdir(parents=True, exist_ok=True)
|
||||
key = load_private_key(Path(args.key))
|
||||
elf = Path(args.baseline_elf).read_bytes()
|
||||
|
||||
container = hostile_signed(hostile_manifest_bytes(), elf, key)
|
||||
(out_dir / "neg_maxmem.mpb").write_bytes(container)
|
||||
write_meta(out_dir, "neg_maxmem", container)
|
||||
print(
|
||||
f"[maxmem-corpus] neg_maxmem declares max_memory_bytes={DECLARED_MAX_MEMORY} "
|
||||
f"(admission must reject pre-init: > {HARD_MAX} hard max)"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env python3
|
||||
"""On-board runner for T8 generation coexistence + admission baseline.
|
||||
|
||||
Drives the poc_a console over /dev/ttyACM0 and asserts the explicit T8
|
||||
markers printed by the firmware:
|
||||
[PASS-v2-candidate-loaded] [PASS-single-candidate-guard]
|
||||
[PASS-both-generations-respond] [PASS-v1-active-60calls]
|
||||
[PASS-swap-unload-old] [PASS-budget-table]
|
||||
plus the per-phase heap snapshots, the >256KiB-requestable positive
|
||||
(baseline_300k), the hostile 600KiB admission negative (neg_maxmem) and the
|
||||
plain baseline_v2 generation positive. Exits non-zero on the first violated
|
||||
assertion.
|
||||
|
||||
`poca coexist` blocks for ~35s (60 x 500ms loop window), so this command
|
||||
gets a longer deadline than the matrix runner's 8s default. Serial session
|
||||
conventions learned in T4/T5: "\\r" line endings, quiesce-based prompt
|
||||
detection, RTS pulse to reboot after opening the port.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import time
|
||||
|
||||
import serial
|
||||
|
||||
PROMPT = "poca> "
|
||||
COEXIST_MARKERS = [
|
||||
"[PASS-v2-candidate-loaded]",
|
||||
"[PASS-single-candidate-guard]",
|
||||
"[PASS-both-generations-respond]",
|
||||
"[PASS-v1-active-60calls]",
|
||||
"[PASS-swap-unload-old]",
|
||||
"[PASS-budget-table]",
|
||||
]
|
||||
HEAP_PHASES = ["baseline", "v1-active", "coexist-peak", "v2-active", "final"]
|
||||
|
||||
|
||||
class Board:
|
||||
def __init__(self, port: str, baud: int = 115200, timeout: float = 1.0) -> None:
|
||||
self.serial = serial.Serial(port, baud, timeout=timeout)
|
||||
self.serial.setRTS(True)
|
||||
time.sleep(0.1)
|
||||
self.serial.setRTS(False)
|
||||
time.sleep(0.1)
|
||||
self.serial.reset_input_buffer()
|
||||
|
||||
def command(self, line: str, settle: float = 0.6, deadline_s: float = 8.0) -> str:
|
||||
self.serial.write((line + "\r").encode())
|
||||
self.serial.flush()
|
||||
time.sleep(settle)
|
||||
deadline = time.monotonic() + deadline_s
|
||||
buf = b""
|
||||
while time.monotonic() < deadline:
|
||||
chunk = self.serial.read(4096)
|
||||
if chunk:
|
||||
buf += chunk
|
||||
tail = buf.decode(errors="replace")
|
||||
if tail.rstrip().endswith(PROMPT.rstrip()):
|
||||
break
|
||||
else:
|
||||
time.sleep(0.1)
|
||||
text = buf.decode(errors="replace")
|
||||
print(f"--- poca> {line}")
|
||||
print(text, end="" if text.endswith("\n") else "\n")
|
||||
return text
|
||||
|
||||
def close(self) -> None:
|
||||
self.serial.close()
|
||||
|
||||
|
||||
def entry_queries(board: Board) -> int:
|
||||
text = board.command("poca status")
|
||||
marker = "entry queries so far: "
|
||||
for line in text.splitlines():
|
||||
if marker in line:
|
||||
return int(line.split(marker)[1].split()[0])
|
||||
raise AssertionError("entry queries marker not found in status output")
|
||||
|
||||
|
||||
def run(port: str) -> int:
|
||||
board = Board(port)
|
||||
failures = []
|
||||
|
||||
def expect(what: str, text: str, needles: list[str]) -> None:
|
||||
for needle in needles:
|
||||
if needle not in text:
|
||||
failures.append(f"{what}: missing '{needle}'")
|
||||
|
||||
expect("status", board.command("poca status"),
|
||||
["registered host imports: poca_host_sentinel poca_host_add",
|
||||
"heap psram", "heap iram-exec"])
|
||||
canary_start = entry_queries(board)
|
||||
|
||||
# T8 generation positive: baseline_v2 (same manifest name "baseline",
|
||||
# version 2.0.0, distinct activate magic).
|
||||
expect("verify v2", board.command("poca verify baseline_v2"),
|
||||
["[poca-verify] baseline_v2 size=", "sha256=", "version=2.0.0",
|
||||
"[poca-verify] PASS"])
|
||||
expect("load v2", board.command("poca load baseline_v2"),
|
||||
["[poca-load] mpb size=", "[poca-load] identity name=baseline version=2.0.0 MATCH",
|
||||
"[poca] admission max_mem=262144", "[poca-load] PASS"])
|
||||
expect("activate v2", board.command("poca activate"), ["MAGIC MATCH"])
|
||||
expect("unload v2", board.command("poca unload"), ["[poca-unload] PASS"])
|
||||
|
||||
# T8 requestable positive: 300KiB declaration (default arena is 256KiB;
|
||||
# hard max is 512KiB -> admissible, MEM-003).
|
||||
expect("verify 300k", board.command("poca verify baseline_300k"),
|
||||
["[poca-verify] baseline_300k size=", "version=1.0.1", "[poca-verify] PASS"])
|
||||
expect("load 300k", board.command("poca load baseline_300k"),
|
||||
["[poca] admission max_mem=307200 default_arena=262144 hard_max=524288 OK",
|
||||
"[poca-load] PASS"])
|
||||
expect("activate 300k", board.command("poca activate"), ["MAGIC MATCH"])
|
||||
expect("unload 300k", board.command("poca unload"), ["[poca-unload] PASS"])
|
||||
|
||||
# T8 admission negative: hostile 600KiB declaration rejected pre-init.
|
||||
expect("load neg_maxmem", board.command("poca load neg_maxmem"),
|
||||
["[poca] admission max_mem=614400 default_arena=262144 hard_max=524288 "
|
||||
"REJECT(>hard max)",
|
||||
"NEGATIVE neg_maxmem PASS (admission: max_memory=614400 > 524288 hard max, "
|
||||
"rejected pre-init)",
|
||||
"entry_queries=", "(unchanged=yes)"])
|
||||
|
||||
canary_mid = entry_queries(board)
|
||||
if canary_mid != canary_start + 2:
|
||||
failures.append(f"canary after v2/300k loads + neg_maxmem: {canary_mid} != "
|
||||
f"{canary_start}+2 (two queries; negative must not execute)")
|
||||
|
||||
# T8 coexistence scenario (long: ~35s blocking).
|
||||
coexist = board.command("poca coexist", settle=1.0, deadline_s=120.0)
|
||||
expect("coexist", coexist, COEXIST_MARKERS + [
|
||||
"[poca-coexist] phase 1: load v1 (baseline 1.0.0) as ACTIVE",
|
||||
"[poca-coexist] identity name=baseline version=1.0.0 MATCH",
|
||||
"[poca-cand] identity name=baseline version=2.0.0 MATCH",
|
||||
"independent arenas",
|
||||
"v1 ACTIVE activate returned=0x",
|
||||
"gen-old activate fn=0x",
|
||||
"gen-new activate fn=0x",
|
||||
"distinct code addresses=yes",
|
||||
"final calls=", "loop final calls=",
|
||||
"[T8-budget] psram baseline_free=",
|
||||
"[T8-budget] headroom vs 8MiB pool:",
|
||||
"[T8-budget] iram-exec baseline_free=",
|
||||
"[poca-coexist] PASS",
|
||||
])
|
||||
for phase in HEAP_PHASES:
|
||||
expect("coexist heap", coexist, [f"[T8-heap] phase={phase} "])
|
||||
expect("coexist stacks", coexist,
|
||||
["[T8-stack] phase=baseline", "[T8-stack] phase=coexist-peak", "poca_gen",
|
||||
"[T8-stack] "])
|
||||
|
||||
# Post-scenario clean state: plain load/activate/unload still works.
|
||||
expect("post load", board.command("poca load baseline"), ["[poca-load] PASS"])
|
||||
expect("post activate", board.command("poca activate"), ["MAGIC MATCH"])
|
||||
expect("post unload", board.command("poca unload"), ["[poca-unload] PASS"])
|
||||
|
||||
final_status = board.command("poca status")
|
||||
expect("final status", final_status, ["heap psram", "heap iram-exec"])
|
||||
|
||||
board.close()
|
||||
|
||||
if failures:
|
||||
print("\nCOEXIST FAILURES:")
|
||||
for failure in failures:
|
||||
print(f" - {failure}")
|
||||
return 1
|
||||
print(f"\nCOEXIST PASS (6/6 markers, {len(HEAP_PHASES)} heap phases, "
|
||||
f"300KiB requestable + 600KiB rejected, canary start={canary_start})")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--port", default="/dev/ttyACM0")
|
||||
args = parser.parse_args()
|
||||
return run(args.port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user