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:
Lain
2026-09-07 20:02:18 +08:00
committed by GitHub
co-authored by lain
parent 0018ebbb8f
commit e71842aa8a
163 changed files with 97525 additions and 50 deletions
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""Handcrafted negative corpus for the T5 relocation/import allowlist matrix.
The positive pipeline gates (check_plugin_elf.cmake) reject every image this
script produces, by design: the gates protect positive builds, negatives are
handcrafted. What the script fabricates, starting from the genuine gated
`baseline.elf` (each fixture is a deterministic byte patch, re-signed with
the TEST-only key, so the device-side mpb verification passes and the
rejection must come from the loader/policy layers):
neg_r32 first .rela.dyn entry's relocation type patched to
R_XTENSA_32 (1) -> loader must fail with -EINVAL (patch p1)
neg_s0op same entry patched to R_XTENSA_SLOT0_OP (20)
-> loader must fail with -EINVAL (patch p1)
neg_phbe e_ident[EI_DATA] = big-endian -> loader must fail with
-EINVAL (patch p2)
neg_ph64 e_ident[EI_CLASS] = ELF64 -> loader must fail with
-EINVAL (patch p2)
neg_phmach e_machine = 40 (EM_ARM) -> loader must fail with
-EINVAL (patch p2)
neg_phspan first PT_LOAD p_memsz inflated to 15 MiB -> harness
program-header admission check must reject the load before
esp_elf_init (segment budget > manifest max_memory_bytes)
Toolchain note (recorded in ALLOWLIST.md): xtensa ld canonicalizes or
rejects fabricated out-of-allowlist dynamic relocations at link time
(R_XTENSA_32 against a dynamic symbol becomes R_XTENSA_GLOB_DAT;
R_XTENSA_SLOT0_OP is a "dangerous relocation" hard error), so the reloc
negatives are post-link patches of a real .rela.dyn entry rather than
compiler-emitted ones.
The EI_DATA/EI_CLASS/e_machine fixtures cannot go through `build_mpb`
because the manifest builder itself validates class/endian/machine in
extract_plugin_iram_size(); those three are assembled with assemble_mpb()
plus the deterministic signer (the "hostile_signed" pattern proven in
tests/test_manifest_builder).
"""
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,
Manifest,
Payload,
assemble_mpb,
build_mpb,
derive_key_id,
load_private_key,
)
SHT_RELA = 4
PT_LOAD = 1
EM_ARM = 40
R_XTENSA_32 = 1
R_XTENSA_SLOT0_OP = 20
EI_CLASS, EI_DATA = 4, 5
MAX_MEMORY_BYTES = 262144
PHSPAN_MEMSZ = 0x00F00000
def ehdr_fields(elf: bytes) -> dict[str, int]:
(phoff, shoff) = struct.unpack_from("<II", elf, 28)
(phentsize, phnum, shentsize, shnum) = struct.unpack_from("<HHHH", elf, 42)
return {
"phoff": phoff,
"shoff": shoff,
"phentsize": phentsize,
"phnum": phnum,
"shentsize": shentsize,
"shnum": shnum,
}
def first_rela_entry(elf: bytes) -> int:
"""File offset of the first Elf32_Rela entry of the first SHT_RELA section."""
fields = ehdr_fields(elf)
for index in range(fields["shnum"]):
shdr = struct.unpack_from("<10I", elf, fields["shoff"] + index * fields["shentsize"])
if shdr[1] == SHT_RELA and shdr[5] >= 12:
return shdr[4]
raise SystemExit("baseline.elf carries no SHT_RELA section; cannot patch")
def patch_reloc_type(elf: bytes, new_type: int) -> bytes:
entry = first_rela_entry(elf)
r_offset, r_info = struct.unpack_from("<II", elf, entry)
buf = bytearray(elf)
buf[entry + 4] = new_type # low byte of r_info on little-endian ELF32
patched_info = (r_info & 0xFFFFFF00) | new_type
print(f" rela@0x{entry:04x}: r_offset=0x{r_offset:08x} r_info=0x{r_info:08x}"
f" -> 0x{patched_info:08x} (type {r_info & 0xFF} -> {new_type})")
return bytes(buf)
def first_pt_load_memsz_field(elf: bytes) -> int:
fields = ehdr_fields(elf)
for index in range(fields["phnum"]):
phdr = struct.unpack_from("<8I", elf, fields["phoff"] + index * fields["phentsize"])
if phdr[0] == PT_LOAD:
return fields["phoff"] + index * fields["phentsize"] + 5 * 4
raise SystemExit("baseline.elf carries no PT_LOAD segment")
def patch_phspan(elf: bytes) -> bytes:
field = first_pt_load_memsz_field(elf)
old = struct.unpack_from("<I", elf, field)[0]
buf = bytearray(elf)
struct.pack_into("<I", buf, field, PHSPAN_MEMSZ)
print(f" phdr p_memsz@0x{field:04x}: {old} -> {PHSPAN_MEMSZ}")
return bytes(buf)
def patch_header(elf: bytes, offset: int, value: int, what: str) -> bytes:
buf = bytearray(elf)
old = buf[offset]
buf[offset] = value
print(f" {what}@0x{offset:02x}: {old} -> {value}")
return bytes(buf)
def sign_with_assemble(name: str, elf: bytes, key) -> bytes:
manifest = Manifest(name, "1.0.0")
manifest.set("max_memory_bytes", MAX_MEMORY_BYTES)
manifest.set("iram_required_bytes", 0)
return assemble_mpb(
manifest_bytes=manifest.encode(),
payloads=[Payload(kind=PAYLOAD_TYPE_ELF, data=elf)],
key_id=derive_key_id(key.public_key()),
flags=0,
security_epoch=1,
signing_key=key,
)
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/negative/build_negative_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 \"{name}\"\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"[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()
out_dir = Path(args.out_dir)
(out_dir / "generated").mkdir(parents=True, exist_ok=True)
key = load_private_key(Path(args.key))
baseline = Path(args.baseline_elf).read_bytes()
buildable = {
"neg_r32": lambda: patch_reloc_type(baseline, R_XTENSA_32),
"neg_s0op": lambda: patch_reloc_type(baseline, R_XTENSA_SLOT0_OP),
"neg_phspan": lambda: patch_phspan(baseline),
}
for name, make in buildable.items():
print(f"[corpus] building {name}")
elf = make()
manifest = Manifest(name, "1.0.0")
manifest.set("max_memory_bytes", MAX_MEMORY_BYTES)
container = build_mpb(
manifest,
[Payload(kind=PAYLOAD_TYPE_ELF, data=elf)],
signing_key=key,
security_epoch=1,
)
(out_dir / f"{name}.mpb").write_bytes(container)
write_meta(out_dir, name, container)
header_only = {
"neg_phbe": lambda: patch_header(baseline, EI_DATA, 2, "EI_DATA"),
"neg_ph64": lambda: patch_header(baseline, EI_CLASS, 2, "EI_CLASS"),
"neg_phmach": lambda: patch_header(
baseline, 18, EM_ARM, "e_machine(low byte)"
),
}
for name, make in header_only.items():
print(f"[corpus] building {name} (assemble_mpb hostile-signed path)")
elf = make()
container = sign_with_assemble(name, elf, key)
(out_dir / f"{name}.mpb").write_bytes(container)
write_meta(out_dir, name, container)
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""On-board runner for the T5 relocation/import allowlist matrix.
Drives the poc_a console over /dev/ttyACM0 and asserts, per matrix row, the
explicit PASS/NEGATIVE markers printed by the firmware plus the
entry-query canary count (which must stay unchanged across all negatives —
nothing may execute). Exits non-zero on the first violated assertion.
Serial session conventions learned in T4: "\r" line endings, quiesce-based
prompt detection (log lines interleave after the first prompt), RTS pulse
to reboot after opening the port.
"""
from __future__ import annotations
import argparse
import sys
import time
import serial
PROMPT = "poca> "
POSITIVE_CYCLE = ["baseline", "globdat", "plt"]
NEGATIVES = [
("import_neg", ["NEGATIVE import_neg PASS (errno -88, expected -88)"]),
("neg_r32", ["NEGATIVE neg_r32 PASS (errno -22, expected -22)"]),
("neg_s0op", ["NEGATIVE neg_s0op PASS (errno -22, expected -22)"]),
("neg_phbe", ["NEGATIVE neg_phbe PASS (errno -22, expected -22)"]),
("neg_ph64", ["NEGATIVE neg_ph64 PASS (errno -22, expected -22)"]),
("neg_phmach", ["NEGATIVE neg_phmach PASS (errno -22, expected -22)"]),
("neg_phspan", ["NEGATIVE neg_phspan PASS (phdr admission rejected before load)"]),
("cxx_ctor", ["NEGATIVE cxx_ctor PASS (errno -22, expected -22)",
"Forbidden C++ feature section"]),
("cxx_tls", ["NEGATIVE cxx_tls PASS (errno -22, expected -22)",
"Forbidden C++ feature section"]),
("neg_tls_nosect", ["NEGATIVE neg_tls_nosect PASS (errno -22, expected -22)",
"Failed to relocate type"]),
]
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) -> str:
self.serial.write((line + "\r").encode())
self.serial.flush()
time.sleep(settle)
deadline = time.monotonic() + 8.0
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"])
canary_start = entry_queries(board)
for name in POSITIVE_CYCLE:
expect(f"verify {name}", board.command(f"poca verify {name}"),
[f"[poca-verify] {name} size=", "phdr loads=", "[poca-verify] PASS"])
load = board.command(f"poca load {name}")
expect(f"load {name}", load,
["[poca-load] mpb size=", "sha256=", "[poca-load] PASS"])
if name == "globdat":
expect("globdat value", load, ["GLOB_DAT host_sentinel=0x", " MATCH"])
if name == "plt":
expect("plt value", load, ["GLOB_DAT host_add=0x", " MATCH"])
expect(f"activate {name}", board.command("poca activate"),
["MAGIC MATCH", "[poca-activate] PASS"])
expect(f"unload {name}", board.command("poca unload"), ["[poca-unload] PASS"])
canary = entry_queries(board)
if canary != canary_start + len(POSITIVE_CYCLE):
failures.append(f"canary after positives: {canary} != "
f"{canary_start}+{len(POSITIVE_CYCLE)}")
for name, needles in NEGATIVES:
expect(f"load {name}", board.command(f"poca load {name}"),
needles + ["entry_queries=", "(unchanged=yes)"])
canary_neg = entry_queries(board)
if canary_neg != canary:
failures.append(f"canary after negatives: {canary_neg} != {canary} (executed bytes!)")
expect("re-load baseline", board.command("poca load baseline"), ["[poca-load] PASS"])
expect("re-activate", board.command("poca activate"), ["MAGIC MATCH"])
expect("re-unload", board.command("poca unload"), ["[poca-unload] PASS"])
board.close()
if failures:
print("\nMATRIX FAILURES:")
for failure in failures:
print(f" - {failure}")
return 1
print(f"\nMATRIX PASS (positives={len(POSITIVE_CYCLE)}, negatives={len(NEGATIVES)}, "
f"canary={canary_neg} unchanged across all negatives, "
f"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())