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,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""T7 IRAM corpus builder: budget-mismatch negative + IRAM contract gate.
|
||||
|
||||
Starting from the gate-approved iram_probe.elf (check_plugin_elf.cmake ran
|
||||
on it, including the .plugin_iram section gates; the positive iram_probe.mpb
|
||||
itself comes from the poca_plugin pipeline), this script:
|
||||
|
||||
1. verifies the IRAM section contract that the section-table gates cannot
|
||||
see: the disassembly of .plugin_iram must contain no l32r literal load.
|
||||
An l32r executed from the IRAM window would fetch its literal from the
|
||||
PSRAM text window, beyond the 256 KB backward-only l32r reach - a
|
||||
runtime-only fault, so it is rejected here, at build time;
|
||||
2. builds the negative container iram_mismatch: same ELF, manifest
|
||||
declares iram_required_bytes = section size + 16. This must go through
|
||||
assemble_mpb (the hostile_signed pattern proven in T5/T6) because
|
||||
build_mpb itself refuses a declared value that disagrees with the
|
||||
extracted section size. The device-side rejection must then come from
|
||||
loader patch p5, before any allocation and before any plugin byte
|
||||
executes (PLUG-009 / MEM 4.2.4 budget consistency).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import re
|
||||
import subprocess
|
||||
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,
|
||||
derive_key_id,
|
||||
load_private_key,
|
||||
)
|
||||
|
||||
MISMATCH_DELTA = 16
|
||||
MAX_MEMORY_BYTES = 262144
|
||||
|
||||
|
||||
def check_iram_contract(elf_path: Path, objdump: str) -> int:
|
||||
"""Assert .plugin_iram exists, has no l32r, no split subsections.
|
||||
|
||||
Returns the section size."""
|
||||
sections = subprocess.run(
|
||||
[objdump, "-h", str(elf_path)], check=True, capture_output=True, text=True
|
||||
).stdout
|
||||
iram_rows = [line for line in sections.splitlines() if re.search(r"\s\.plugin_iram\s", line)]
|
||||
extras = [line for line in sections.splitlines() if re.search(r"\s\.plugin_iram\.\S+\s", line)]
|
||||
if extras:
|
||||
names = " ".join(re.search(r"(\S*\.plugin_iram\.\S*)\s", line).group(1) for line in extras)
|
||||
raise SystemExit(
|
||||
f"[iram-corpus] FAIL iram_probe: split IRAM subsections present: {names} "
|
||||
"(literal pools must not leak out of .plugin_iram)"
|
||||
)
|
||||
if not iram_rows:
|
||||
raise SystemExit("[iram-corpus] FAIL iram_probe: no .plugin_iram section in image")
|
||||
|
||||
disasm = subprocess.run(
|
||||
[objdump, "-d", "-j", ".plugin_iram", str(elf_path)],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout
|
||||
literals = [line.strip() for line in disasm.splitlines() if re.search(r"\bl32r\b", line)]
|
||||
if literals:
|
||||
raise SystemExit(
|
||||
"[iram-corpus] FAIL iram_probe: l32r literal load inside .plugin_iram "
|
||||
f"(unreachable across the IRAM/PSRAM window split): {'; '.join(literals)}"
|
||||
)
|
||||
|
||||
size = int(iram_rows[0].split()[2], 16)
|
||||
print(f"[iram-corpus] iram contract OK: .plugin_iram size={size} l32r=0 subsections=0")
|
||||
return size
|
||||
|
||||
|
||||
def write_meta(out_dir: Path, name: str, container: bytes) -> None:
|
||||
digest = hashlib.sha256(container).hexdigest()
|
||||
upper = name.upper()
|
||||
generated_by = "poc/apps/poc_a/plugins/iram_probe/build_iram_corpus.py"
|
||||
header = (
|
||||
f"/* Generated by {generated_by} - 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"[iram-corpus] {name}.mpb size={len(container)} sha256={digest}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--probe-elf", required=True)
|
||||
parser.add_argument("--objdump", 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))
|
||||
elf = Path(args.probe_elf).read_bytes()
|
||||
|
||||
section_size = check_iram_contract(Path(args.probe_elf), args.objdump)
|
||||
|
||||
mismatch = Manifest("iram_mismatch", "1.0.0")
|
||||
mismatch.set("max_memory_bytes", MAX_MEMORY_BYTES)
|
||||
mismatch.set("iram_required_bytes", section_size + MISMATCH_DELTA)
|
||||
negative = assemble_mpb(
|
||||
manifest_bytes=mismatch.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,
|
||||
)
|
||||
(out_dir / "iram_mismatch.mpb").write_bytes(negative)
|
||||
write_meta(out_dir, "iram_mismatch", negative)
|
||||
print(
|
||||
f"[iram-corpus] iram_mismatch declares iram_required_bytes="
|
||||
f"{section_size}+{MISMATCH_DELTA} (loader p5 must reject pre-allocate)"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* IRAM probe plugin (task T7 of poc-a-dynamic-elf).
|
||||
*
|
||||
* Same freestanding C contract as the baseline plugin (plugins.cmake
|
||||
* pipeline, narrow relocation allowlist), plus a .plugin_iram section: the
|
||||
* two iram_* functions below are placed into internal executable RAM by
|
||||
* the patched loader and the entry table hands their native 0x40.. window
|
||||
* addresses back to the firmware.
|
||||
*
|
||||
* IRAM SECTION CONTRACT (violation = runtime-only fault, asserted at build
|
||||
* time by build_iram_corpus.py): the iram_* functions must contain no l32r
|
||||
* literal and no static reference. Every large constant arrives as a
|
||||
* parameter; an l32r pool for .plugin_iram code would be placed in the
|
||||
* PSRAM text window, beyond the 256 KB backward-only l32r reach from the
|
||||
* IRAM window.
|
||||
*/
|
||||
|
||||
#include "plugin_abi.h"
|
||||
|
||||
#define IRAM_PROBE_ERR_ABI_MISMATCH (-7)
|
||||
#define IRAM_PROBE_ERR_PACKAGE_INVALID (-18)
|
||||
#define IRAM_PROBE_ERR_HASH_MISMATCH (-19)
|
||||
|
||||
static int32_t iram_probe_prepare(void);
|
||||
static int32_t iram_probe_activate(void);
|
||||
static int32_t iram_probe_unload(void);
|
||||
static uint32_t iram_check_impl(uint32_t magic, uint32_t mult, uint32_t seed, uint32_t poly,
|
||||
uint32_t words);
|
||||
static int32_t iram_write_impl(uint32_t* dst, uint32_t value);
|
||||
static uint32_t* iram_data_word_ptr(void);
|
||||
static uint32_t iram_data_word_read(void);
|
||||
|
||||
/* The write-visibility probe target: a plain .data word, so the loader
|
||||
* places it in the PSRAM data window and IRAM-resident stores to it must
|
||||
* be observable through every other window. */
|
||||
static uint32_t g_probe_word = 0x13572468u;
|
||||
|
||||
__attribute__((section(".plugin_iram"), noinline, used)) static uint32_t
|
||||
iram_check_impl(uint32_t magic, uint32_t mult, uint32_t seed, uint32_t poly, uint32_t words) {
|
||||
/* Check value: magic ^ fold over a small table built on the stack from
|
||||
* the caller-chosen parameters (poca_iram_fold in plugin_abi.h defines
|
||||
* the algorithm; the firmware recomputes the expected value with its
|
||||
* own flash-resident copy of the same code). */
|
||||
uint32_t tbl[16];
|
||||
uint32_t acc = seed;
|
||||
for (uint32_t i = 0; i < words && i < 16u; ++i) {
|
||||
acc = acc * mult + i + 1u;
|
||||
tbl[i] = acc ^ (poly >> (i & 7u));
|
||||
}
|
||||
uint32_t v = magic;
|
||||
for (uint32_t i = 0; i < words && i < 16u; ++i) {
|
||||
v = (v << 3) | (v >> 29);
|
||||
v ^= tbl[i] + magic;
|
||||
}
|
||||
return v ^ seed;
|
||||
}
|
||||
|
||||
__attribute__((section(".plugin_iram"), noinline, used)) static int32_t
|
||||
iram_write_impl(uint32_t* dst, uint32_t value) {
|
||||
*dst = value;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static uint32_t* iram_data_word_ptr(void) { return &g_probe_word; }
|
||||
|
||||
static uint32_t iram_data_word_read(void) { return g_probe_word; }
|
||||
|
||||
static int32_t iram_probe_prepare(void) {
|
||||
if (POCA_BASELINE_PATTERN[0] != 0xA5u || POCA_BASELINE_PATTERN[63] != 0x5Au) {
|
||||
return IRAM_PROBE_ERR_PACKAGE_INVALID;
|
||||
}
|
||||
uint32_t first = poca_crc32(POCA_BASELINE_PATTERN, POCA_BASELINE_PATTERN_SIZE);
|
||||
if (first == 0u) {
|
||||
return IRAM_PROBE_ERR_HASH_MISMATCH;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int32_t iram_probe_activate(void) {
|
||||
return (int32_t)(POCA_PLUGIN_MAGIC ^
|
||||
poca_crc32(POCA_BASELINE_PATTERN, POCA_BASELINE_PATTERN_SIZE));
|
||||
}
|
||||
|
||||
static int32_t iram_probe_unload(void) { return 0; }
|
||||
|
||||
static const poca_plugin_table_t k_iram_table = {
|
||||
.struct_size = (uint32_t)sizeof(poca_plugin_table_t),
|
||||
.abi_major = POCA_PLUGIN_ABI_MAJOR,
|
||||
.abi_minor = POCA_PLUGIN_ABI_MINOR,
|
||||
.prepare = &iram_probe_prepare,
|
||||
.activate = &iram_probe_activate,
|
||||
.unload = &iram_probe_unload,
|
||||
.state_schema_id = 0u,
|
||||
.state_schema_version = 0u,
|
||||
.iram_check = &iram_check_impl,
|
||||
.iram_write = &iram_write_impl,
|
||||
.data_word_ptr = &iram_data_word_ptr,
|
||||
.data_word_read = &iram_data_word_read,
|
||||
};
|
||||
|
||||
__attribute__((visibility("default"))) const poca_plugin_table_t* frame_plugin_entry(void) {
|
||||
return &k_iram_table;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"max_memory_bytes": 262144
|
||||
}
|
||||
Reference in New Issue
Block a user