Skip to content

fix: repair master — the ABI asserts and the Ed25519 verifier both merged broken - #94

Merged
srpatcha merged 1 commit into
embeddedos-org:masterfrom
Kartikey1306:fix/master-image-abi-asserts
Sep 8, 2026
Merged

srpatcha merged 1 commit into
embeddedos-org:masterfrom
Kartikey1306:fix/master-image-abi-asserts

Conversation

@Kartikey1306

Copy link
Copy Markdown
Contributor

master (22d8f8b) does not compile. Two independent double-merges, both the same shape: two PRs fixing adjacent things landed on stale bases, each green on its own branch, and the merged result was never rebuilt.

$ cmake -S . -B build -DEBLDR_BUILD_TESTS=ON && cmake --build build
include/eos_image.h:135:23: error: no member named 'reserved' in 'eos_image_header_t'
include/eos_image.h:142:57: error: no member named 'reserved' in 'eos_image_header_t'
core/ed25519_verify.c:338:12: error: redefinition of 'point_is_identity'

This blocks every open PR that builds the test suite.

1. include/eos_image.h — #93 and #87

#93 replaced reserved[30] with tlv_len (2 bytes) + tlv_hash[28], preserving every offset. #87 merged afterwards carrying asserts written against the older struct.

#93 already asserts tlv_len at 62 and tlv_hash at 64, so #87's offset assert was a duplicate. Its width assert had no replacement, and that is the one that matters — an offset assert cannot see a field growing into padding that keeps every later offset. Restored as two asserts covering both halves of the same 30-byte span. No offset moves; the wire format is unchanged.

2. core/ed25519_verify.c — #86 and #57

Both landed a subgroup guard, so the file carried two byte-identical point_is_identity() definitions. Only #57's public_key_is_valid_subgroup() is wired to the call site, so #86's key_has_prime_order() was dead code. Kept the live function, folded #86's fuller rationale onto it, deleted the duplicate.

3. tests/unit/test_ed25519.c — collateral from the same merge

Two copies of test_ed25519_identity_key_forgery_rejected; main() calling it twice and two tests not at all; and test_ed25519_low_order_R_with_a_valid_key_is_not_a_forgery referencing k_low_order[] and messages[] that the merge had dropped.

While restoring the corpus, corrected it — this is the review finding on #86. The array claimed to hold "the eight low-order point encodings" and held five. Every order below was computed, not copied: decode y, recover x, add the point to itself until it reaches the identity.

encoding order in the old array?
01 00…00 1 (identity) yes
ECFF…FF7F 2 yes
00…00 4 yes
00…0080 4 no
26E8…6D53FC05 8 yes
C717…92AC037A 8 yes
26E8…6D53FC85 8 no
C717…92AC03FA 8 no
D9FF…FF does not decode yes — and it is not a low-order point

D9FF…FF moves to a separate k_non_canonical[] alongside EDFF…FF7F (y = p) and EEFF…FF7F (y = p+1). [L](-A) = -[L]A so the guard rejects a sign variant whether or not it is listed — the reason to list them is that this is the regression record for a Critical secure-boot bypass, and a claimed class has to be the class it claims.

tests_run was assigned a literal (11) in main() and never incremented, which is exactly how a duplicate call and two unregistered tests went unnoticed. The TEST macro now increments it, so the total cannot drift from what actually ran.

Verification

check before after
cmake --build (EBLDR_BUILD_TESTS=ON) 3 errors clean
ctest could not build 21/21 PASS
ctest under -DEBLDR_SANITIZE=ON (ASan+UBSan) — 21/21 PASS
pytest tests/ — 24 passed, 1 skipped
test_ed25519 11 claimed, 12 run, 1 twice 14/14 PASS

The sweep still discriminates. With public_key_is_valid_subgroup() disabled:

test_ed25519_low_order_keys_rejected            [FAIL]   <- as it must
test_ed25519_non_canonical_encodings_rejected   [PASS]   <- different mechanism

That second line is why the two arrays are separate: the non-canonical encodings are refused by unpackneg() on canonicality, not by the subgroup check, so nobody should delete that path believing the subgroup test now covers it.

Refs #87, #93, #86, #57

…rged broken

master (22d8f8b) does not compile. Two independent double-merges, both the
same shape: two PRs fixing adjacent things landed on stale bases, each was
green on its own branch, and the result was never rebuilt.

1. include/eos_image.h — embeddedos-org#93 replaced reserved[30] with tlv_len (2) +
   tlv_hash[28], preserving every offset. embeddedos-org#87 merged afterwards carrying
   asserts written against the older struct:

     error: no member named 'reserved' in 'eos_image_header_t'   (x2)

   embeddedos-org#93 already asserts tlv_len at 62 and tlv_hash at 64, so the offset assert
   was a duplicate; the width assert had no replacement and is restored as two
   asserts covering both halves of the same 30-byte span. No offset moves and
   the wire format is unchanged.

2. core/ed25519_verify.c — embeddedos-org#86 and embeddedos-org#57 both landed a subgroup guard, so the
   file carried two byte-identical point_is_identity() definitions:

     error: redefinition of 'point_is_identity'

   Only embeddedos-org#57's public_key_is_valid_subgroup() is wired to the call site, so
   embeddedos-org#86's key_has_prime_order() was dead. Kept the live function, folded embeddedos-org#86's
   fuller rationale onto it, deleted the duplicate.

3. tests/unit/test_ed25519.c — collateral from the same merge. Two copies of
   test_ed25519_identity_key_forgery_rejected, main() calling it twice and two
   tests not at all, and test_ed25519_low_order_R_with_a_valid_key_is_not_a_forgery
   referencing k_low_order[] and messages[] that the merge had dropped.

   While restoring the corpus, corrected it (review finding on embeddedos-org#86): the array
   claimed to hold "the eight low-order point encodings" and held five. Every
   order here was computed rather than copied — decode y, recover x, add the
   point to itself until it reaches the identity — giving 1, 2, 4, 4, 8, 8, 8,
   8. Missing before: y=0 with the sign bit set, and both sign-flipped order-8
   encodings. D9FF..FF was in the array and is not a low-order point at all —
   no x satisfies the curve equation for that y — so it moves to a separate
   k_non_canonical[], with EDFF..FF7F (y=p) and EEFF..FF7F (y=p+1).

   tests_run was assigned a literal (11) in main() and never incremented,
   which is how the duplicate call and the two unregistered tests went
   unnoticed. The TEST macro now increments it, so the total cannot drift.

Verified:
  cmake -DEBLDR_BUILD_TESTS=ON on master   FAILS to build, 3 errors
  same with this commit                    builds clean
  ctest                                    21/21 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   21/21 PASS
  pytest tests/                            24 passed, 1 skipped
  test_ed25519                             14/14 PASS (was 11 claimed, 12 run)
  discrimination, with `public_key_is_valid_subgroup` disabled:
    test_ed25519_low_order_keys_rejected   FAILS, as it must
    test_ed25519_non_canonical_...         still PASSES — those are refused by
      unpackneg() on canonicality, a different mechanism, which is the reason
      they are held in a separate array rather than counted among the eight.
@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Kartikey1306 added a commit to Kartikey1306/eBoot that referenced this pull request Sep 3, 2026
… clash

Three findings from the review on embeddedos-org#80, all in files this branch already owns.

Finding 2 (Medium) -- core/fw_decrypt.c's file header still read "Falls back
to HAL hw_aes_decrypt if available." The diff started at line 192, so that
line survived and directly contradicted the twenty-line rationale this PR
installs below it. A self-contradictory file is worse than the original.

Finding 1 (Medium) -- after the removal, hw_aes_decrypt has zero call sites
while eos_hal.h still advertises it under "software fallback used if NULL",
which is now false in the other direction: a board author who implements the
hook gets nothing, silently, with no diagnostic. That is the same class of
failure this PR is fixing. Kept the member rather than deleting it -- removing
it from a public struct is an ABI change for out-of-tree boards, and the hook
is worth having once it can express the operation -- and documented it as
reserved and currently unconsumed, with the reason and with what a
streaming-capable replacement would need.

Finding 3 (Low) -- this PR and embeddedos-org#82 both inserted their add_executable/add_test
triple immediately after add_test(NAME test_keystore ...), so whichever landed
second would have conflicted for no reason but placement. Re-anchored this
one to the end of the registrations, with a comment saying why.

Also rebased: this branch was 7 commits behind and its diff against current
master would have reverted the test_recovery link-line fix. It is now stacked
on embeddedos-org#94, which repairs master -- without that, every PR that builds the test
suite is red on include/eos_image.h and core/ed25519_verify.c.

Verified:
  cmake --build (EBLDR_BUILD_TESTS=ON)   clean
  ctest                                  22/22 PASS
  test_fw_decrypt                        8/8 PASS
  git grep hw_aes_decrypt                header + this file's comment only

Refs embeddedos-org#80
Kartikey1306 added a commit to Kartikey1306/eBoot that referenced this pull request Sep 3, 2026
…hdr_size

Answers the review on embeddedos-org#88. Both High findings had the same root, and master
has since settled the question the reviewer said needed a decision.

The original defect is real and unchanged: the tool emitted
[header][TLV][payload] while stamping hdr_size as a fixed 156, so
core/image_verify.c's `payload_addr = addr + hdr->hdr_size` landed on the TLV
block and every image it produced failed integrity verification on-device.

This branch fixed it by moving hdr_size to mean "offset to the payload". That
was the wrong half to move.

Finding 1 (High) -- eFirmware/src/efw_image.c:122 checks
`hdr_size != EFW_IMAGE_HDR_SIZE` for exact equality against 156, so every TLV
image would have been rejected by the other half of the format, which
eFirmware's header documents as interchangeable.

Finding 2 (High) -- core/rollback.c computes the TLV address as
image_addr + hdr_size + image_size, i.e. it assumes the area follows the
payload. Under either the old layout or this branch's, the anti-rollback
EOS_TLV_MIN_SEC_VER could never be found, so the counter this repository gates
downgrades on was unreachable for every image the tool produced.

Master answers both, and it is the reviewer's option (b): embeddedos-org#93 landed tlv_len
and tlv_hash in the header -- inside EOS_IMG_SIGNED_LEN -- and documents that
"the TLV area sits after the payload". So this PR now emits
[header][payload][TLV] with hdr_size always 156. eFirmware's equality check
keeps working untouched, rollback.c's arithmetic is correct as written, and no
field changes meaning.

That reordering also resolves an ordering problem the old shape had: the TLV
carried the signature, so its digest could not be computed before the
signature existed. The signature now lives in the header's signature[] field
and the TLV carries metadata only, which is what makes tlv_hash signable.

Finding 4 (Medium) -- the two `assert`s in cmd_sign are removed by `python -O`.
This is release-signing tooling, so the signature-length check is now a
`raise SystemExit`. The TLV-length assert is gone with the code that needed it.

Finding 5 (Medium) -- `pytest.importorskip("cryptography")` still skipped
silently if the install ever failed, leaving "collected 19, ran 0" as a green
run. Now gated: EOS_REQUIRE_SIGNING_TESTS is set in ci.yml, and under it the
module is imported directly so a missing dependency is a collection error.
Locally, without the variable, the skip still applies.

Finding 6 (Low) -- cmd_verify bounds-checks the image length before unpacking,
so a short file gets a FAIL: line rather than a struct.error traceback, and
the 156 is hoisted to EOS_IMG_STRUCT_SIZE rather than re-derived.

Finding 3 (Medium) needs no change here: master's include/eos_image.h already
documents the layout this now emits.

Rebased onto embeddedos-org#94 (the master repair) and reduced to the five files that are
still this PR's own -- the branch was stale enough that its diff against
master would have reverted core/rollback.c, include/eos_image.h,
tests/unit/test_tlv_auth.c and the rest of embeddedos-org#93's TLV work.

Verified:
  end to end, with the real tool:
      eos_sign.py keygen / sign / verify  -> VERIFIED
      total 744 = 156 header + 512 payload + 76 TLV
      hdr_size 156, tlv_len 76, TLV magic 0x6907 at 156+512
      sha256(tlv)[:28] == header bytes 64..92          True
  ctest                                    22/22 PASS
  test_eos_sign_boot_path (real parser over real tool output):
      current layout [hdr][payload][tlv]: verify_integrity -> 0   PASS
      old layout     [hdr][tlv][payload]: verify_integrity -> -3  PASS
      TLV magic at addr + hdr_size + image_size: 0x6907           PASS
    that third line is finding 2's regression test -- it fails on the old
    layout, where the address lands past the end of the image.
  pytest tests/ (EOS_REQUIRE_SIGNING_TESTS=1)          44 passed
  the CI gate itself: with the variable set and the module absent, the import
    raises ImportError -> collection error -> job fails, rather than skipping.

Refs embeddedos-org#88, embeddedos-org#93

@srpatcha srpatcha left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — eBoot#94 "fix: repair master — the ABI asserts and the Ed25519 verifier both merged broken"

head: f704d87 author: Kartikey1306 ci: pass

Verdict: Correct, and every claim in the body checks out — I reproduced the breakage on master, reproduced the repair, and independently recomputed the low-order point orders rather than taking the table on trust. This is the base of the #84 → #85 and #89 stacks and blocks all of them. One finding, and it is about what the PR deliberately does not do.

Findings

# Severity File:line Finding Recommended fix
1 Medium org branch protection, not a file in this diff The body diagnoses the cause precisely — "two PRs fixing adjacent things landed on stale bases, each green on its own branch, and the merged result was never rebuilt" — and then repairs only the damage. Nothing here stops the third occurrence, and this PR is already fixing two independent instances of it (#87/#93 and #86/#57). Every required check in checks.txt runs against the PR head; none runs against the merge result, so two green PRs can and did produce a red master. Not a code change: enable Require branches to be up to date before merging on master for the required checks, or turn on a merge queue. Worth stating in the PR so it is not lost with the fix. .github/STANDARDS.md §"Release model" defines the branch model but says nothing about merge preconditions — see the proposal appended to .ai/autoreview/proposals/2026-09.md.

Nothing else. The diff does what it says, no check is weakened, nothing is deleted without explanation, and the two files it touches are the two that are broken.

What I verified

The breakage is real. origin/master at 22d8f8b:

$ cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DEBLDR_BUILD_TESTS=ON && cmake --build build
include/eos_image.h:135:23: error: 'eos_image_header_t' has no member named 'reserved'
include/eos_image.h:142:55: error: 'eos_image_header_t' has no member named 'reserved'
gmake: *** [Makefile:101: all] Error 2

$ gcc -fsyntax-only -Iinclude core/ed25519_verify.c
core/ed25519_verify.c:338:12: error: redefinition of 'point_is_identity'
core/ed25519_verify.c:281:12: note: previous definition ...

The repair is complete. At this head, clean build and:

100% tests passed, 0 tests failed out of 21
14/14 tests passed          # test_ed25519

Both numbers match the body exactly.

key_has_prime_order() really was dead. On master the only call site is line 496, if (!public_key_is_valid_subgroup(A)); key_has_prime_order is defined at 313 and never referenced. Deleting the right one of the two.

The retained guard fails closed and does both halves. public_key_is_valid_subgroup() returns point_is_identity(multiple) && !point_is_identity(public_key), and the caller maps a false to EOS_ERR_SIGNATURE. ORDER_L is the real group order — I decoded the 32 bytes at core/ed25519_verify.c:71 and compared against 2^252 + 27742317777372353535851937790883648493: equal.

I recomputed the low-order table rather than trusting it, since it is the regression record for a secure-boot bypass. Decoding each y, recovering x, and repeatedly adding the point to itself until it reaches the identity:

k_low_order[]                            k_non_canonical[]
order 1 identity   order=1  canonical    y = p      decodes, order 4, NOT canonical
order 2            order=2  canonical    y = p+1    decodes, order 1, NOT canonical
order 4 sign clear order=4  canonical    D9FF..FF   no x exists on the curve
order 4 sign set   order=4  canonical
order 8 a          order=8  canonical
order 8 b          order=8  canonical
order 8 a'         order=8  canonical
order 8 b'         order=8  canonical

1, 2, 4, 4, 8, 8, 8, 8 is the whole 8-element torsion subgroup, so the array is now the class it names, and the split is justified on exactly the grounds the body gives: D9FF..FF has no x at all and was never a low-order point, while y = p and y = p+1 decode but are non-canonical and are refused earlier by unpackneg(). Every claim in the body's table holds.

One thing the body understates. It says tests_run "was assigned a literal (11) and never incremented, which is exactly how a duplicate call and two unregistered tests went unnoticed". It was worse than mis-labelling: master's main() makes 13 run_* calls (12 distinct, identity_key_forgery twice), so tests_passed reaches 13 against tests_run = 11 and the binary exits 1. And test_ed25519_low_order_R_with_a_valid_key_is_not_a_forgery is defined at tests/unit/test_ed25519.c:278 on master with zero call sites — a signature-forgery test that never ran. git log -S "tests_run = 11" puts both in 22d8f8b, the same merge, so the exposure is recent rather than long-standing. This PR restores the call and makes the count self-maintaining; that is a weakened check being repaired and belongs in the body.

Architecture conformance

Master design §5.1 and §8: conforms. No dependency changes, no new files, no tier movement. eBoot, Tier 1 – Foundation (§21). The change is confined to restoring the state the two merges destroyed.

.ai/security.md "Fail closed" and "Cryptography — reject invalid and low-order public keys explicitly": this PR is what puts eBoot back on the right side of both. Master today cannot build, so Host Build & Tests on every open PR is testing the PR's own repair rather than the tree.

The design-level gap is §28, "Status, Evidence and Claims Policy". It defines what evidence an artifact needs to claim a state — "Implemented: code and functional tests" — and is silent on the integration gate that keeps the trunk in that state. An org whose master does not compile still satisfies §28 as written, because §28 never asks the question of the merged result. That is a hole in the master design rather than in this PR; proposal appended to .ai/autoreview/proposals/2026-09.md.

Proposed changes

  1. Land this first. #84, #89 and (through #84) #85 are all based on f704d87 and cannot build without it.
  2. Add finding 1 to the body as a follow-up item, or open an issue, so the branch-protection change is not lost once the tree is green again.
  3. Add the two facts above — test_ed25519 exiting 1, and the uncalled forgery test — to §3 of the body. They make the case for the tests_run change stronger than it currently reads.

No code change requested.

Not checked

  • pytest tests/ — "24 passed, 1 skipped". I did not run it; I ran the CMake/ctest path only. Unverified.
  • The disabled-guard experiment. The body shows low_order_keys_rejected [FAIL] / non_canonical_encodings_rejected [PASS] with public_key_is_valid_subgroup() disabled. I did not reproduce it. It is consistent with my own computation — the non-canonical entries are refused by unpackneg() before the subgroup check runs — but consistency is not the same as having run it.
  • Sanitizer run at this head. Body claims 21/21 under -DEBLDR_SANITIZE=ON. I ran ASan/UBSan on #84 (22/22, this commit plus the FDT work) and not separately here.
  • Host x86-64 only. The eight cross-compile and eleven EoSim jobs in checks.txt are green; not reproduced.
  • Why Host Build & Tests was green on master's own merge commits. If test_ed25519 was exiting 1 from 22d8f8b onward, something should have been red. I did not dig into the workflow definitions to find out whether the job runs ctest at all on push, so I cannot tell you whether the signal was missing or merely ignored. Worth someone checking — it is the same question finding 1 asks.

Automated architecture review of f704d87fd445 — scheduled, model claude-opus-5, checked against the EmbeddedOS Master Design v2.0. Advisory only: this reviewer never approves, requests changes, or merges. Reply here to discuss or push back — a wrong finding is a bug worth reporting.

@Kartikey1306

Copy link
Copy Markdown
Contributor Author

Worth flagging for merge priority: this blocks every open PR in eos as well as in this repository.

eos/.github/workflows/eos-simulation.yml:28 checks out embeddedos-org/eBoot at ref: master and builds it. So the EoS Full-Stack Simulation job fails identically on all nine open eos PRs, none of which touch anything related:

Cross-compile ARM64 kernel  Build eBoot (ARM64 qemu_arm64 board)
  eBoot/include/eos_image.h:135:23: error: 'eos_image_header_t' has no member named 'reserved'
  eBoot/include/eos_image.h:142:55: error: 'eos_image_header_t' has no member named 'reserved'

That is this PR's finding 1, reached from the other repository. It is the only failing check on eos #114, #116, #117, #118, #119, #122, #126 and #127 — every other job on all of them is green — and nothing can be done from the eos side, because the workflow builds master, not the PR.

The eBoot side is the same story: #80, #82, #84, #85, #88, #89 and #90 are all stacked on this branch because they cannot build otherwise.

No review shortcut intended — the diff is three files and the evidence is in the body. Just noting that the blast radius is larger than the PR looks.

Kartikey1306 added a commit to Kartikey1306/eBoot that referenced this pull request Sep 3, 2026
… makes

Answers the second review on embeddedos-org#82.

Finding 1 (High) -- step 4, "Verify signing key against OTP root-of-trust",
was the same fail-open this PR removes from step 7, two steps earlier. An
`eos_hal_otp_read()` failure was discarded and boot continued; and when the
read succeeded and the anchor was provisioned, the body of the `if` was
`/* In a full implementation, extract key hash from TLV and compare */`. So a
device whose root of trust *is* provisioned booted an image signed by any key
the image carried, and step 8 recorded EOS_SBOOT_OK.

Implementing the TLV comparison is out of scope, as the review says. The two
things that are in scope are done: a non-EOS_OK otp_read now fails
EOS_SBOOT_ERR_SIGNATURE, and a provisioned anchor that nothing compares
against refuses the boot rather than proceeding. An unprovisioned board
(all-zero anchor) is deliberately unchanged -- there is nothing to check
against, and refusing would brick every board that has not been provisioned.
The comment now states plainly that the step is planned rather than
implemented, which §8.1 asks for and a comment inside an `if` was not.

  No test for those two refusals, deliberately, and the file says why rather
  than leaving it to be discovered. Reaching step 4 requires passing step 3 --
  a real Ed25519 signature checked against the keystore. I wrote the obvious
  test first and it was worthless: with require_signature = true and an
  unsigned fixture the boot fails at step 3 and returns the same
  EOS_SBOOT_ERR_SIGNATURE step 4 returns, so it passed against the unfixed
  code too. I confirmed that by reverting step 4 and watching it still pass.
  A test that cannot fail is worse than none. What is there instead is the
  counter-check that the change does not refuse a boot it should allow.

  The fixture is buildable -- the keystore ships RFC 8032 TEST 1's public key
  and the matching private key is in the RFC -- but that machinery is embeddedos-org#88's
  (tools/gen_signed_image_fixture.py). Worth doing once embeddedos-org#88 lands.

Finding 3 (Low) -- `TEST()` did not increment `tests_run` and `main()`
hardcoded `tests_run = 6`, so a test added to the file but not wired into
`main()` would have been skipped with a zero exit. embeddedos-org#94 removed exactly this
from tests/unit/test_ed25519.c, where a hardcoded 11 was masking two uncalled
tests. Same fix here.

Finding 4 (Low) -- the Valgrind `foreach` is hand-maintained and missed 6 of
22 registered tests. Added test_secure_boot_policy, test_fdt_loader and
test_fw_decrypt. The list being hand-maintained at all is the real defect and
is not fixed here -- it is the same class as the hardcoded count, one level
up.

Finding 2 (Medium), that eos_secure_boot() has no production caller, stands
and is not addressed here; finding 1 makes it sharper rather than resolving
it. Finding 5 (Low) is a PR-body correction.

Verified:
  ctest                          22/22 PASS
  test_secure_boot_policy        7/7 PASS
  step 7 discrimination, still: reverting the step-7 branch fails
    test_secure_boot_refuses_when_the_debug_lock_cannot_be_taken

Refs embeddedos-org#82
Kartikey1306 added a commit to Kartikey1306/eBoot that referenced this pull request Sep 3, 2026
…harnesses

Answers the second review on embeddedos-org#84.

Finding 2 (Medium) -- eos_fdt_validate() and eos_fdt_get_prop() kept an
out-of-bounds read by design. Both dereferenced hdr->totalsize before any
length was known and handed that attacker-controlled value to the _sized form
as its bound, so calling either on a short buffer read past it before a single
check had run. The header called that a caller warrant; a warrant is not a
check, and it is the exact bug this PR exists to fix. Neither had an in-tree
caller.

Removed rather than documented. There is now one form of each entry point and
it always takes the length:

    int eos_fdt_validate(const void *fdt_blob, uint32_t avail);
    int eos_fdt_get_prop(const void *fdt, uint32_t fdt_len, ...);

An exported unsafe twin in a TCB header is a future boot-path caller
reintroducing the bug with no compiler complaint, which is worth more than the
convenience of a one-argument call. eos_fdt_load() already passed max_size.
The test that pinned the wrapper's behaviour is gone with the wrapper, and
get_prop_sized_exact() collapsed into get_prop_exact() since they became the
same function.

Finding 3 (Medium) -- tests/fuzz/ was built by nothing. EBLDR_BUILD_FUZZ
defaults OFF and no job set it, so the harness added here joined five others
that no CI job compiles. A harness that is never built cannot fail to build,
which is how fuzz_devicetree came to declare a function that did not exist and
sit there unnoticed (eos#50).

Adds a `fuzz-build` job: configure with clang, build every harness, and run
each for five seconds over its own generated inputs. That is not a campaign --
it is enough to catch a harness that no longer compiles or crashes at once,
which is the failure this repo has actually had. Note it needs
EBLDR_BUILD_TESTS=ON as well: tests/fuzz/ is added from tests/CMakeLists.txt,
so EBLDR_BUILD_FUZZ alone configures cleanly and builds no harness at all --
the job would have passed having compiled nothing. Found that locally before
writing the job, not after.

  NOT RUN, and this is the honest limit: this host has no libFuzzer runtime
  (libclang_rt.fuzzer_osx.a is absent from the Xcode toolchain), so the link
  step cannot be reproduced here for any harness, old or new. What I verified
  is that CMake configures with both flags and reports all six targets --
  "Fuzz targets: fuzz_image_verify, fuzz_recovery_protocol, fuzz_fw_update,
  fuzz_crypto, fuzz_bootctl, fuzz_fdt" -- and that fuzz_fdt.c passes
  `cc -fsyntax-only`. The link and the smoke run are CI's to show, and this
  job is what makes them visible.

  Coordination note: embeddedos-org#90 adds a `CI Gate` whose needs list is
  [test, build-arm, static-analysis]. Whichever of embeddedos-org#84 and embeddedos-org#90 lands second
  must add fuzz-build to that list -- and embeddedos-org#90's own
  test_gate_covers_every_job_that_runs_on_a_pull_request fails loudly if it is
  not, which is the guard working rather than a trap.

Finding 1 (High) is a PR-body correction, made there: the diff carries embeddedos-org#94's
master repair because this branch is stacked on it, and the body described
only the FDT parser.

Verified:
  ctest                                    22/22 PASS
  pytest tests/                            38 passed
  test_fdt_loader                          13 tests PASS
  grep for a length-free entry point       none remains in the header

Refs embeddedos-org#84
@Kartikey1306

Copy link
Copy Markdown
Contributor Author

This PR is blocking 11 open pull requests in eos, and it is the single
highest-leverage merge in the three repos right now. Evidence, since that is a
claim about other repositories.

The blast radius

eos's .github/workflows/eos-simulation.yml checks out
embeddedos-org/eBoot@master and cross-builds it (Cross-compile ARM64 kernel, qemu_arm64). eBoot master does not compile, so that job fails on
every eos pull request, and Full-stack integration summary fails
downstream of it.

Swept every open eos PR head just now. EoS Full-Stack Simulation is red on:

#114 #115 #116 #117 #118 #119 #121 #122 #126 #127 #129

— eleven, all with the identical signature:

eBoot/include/eos_image.h:135: error: 'eos_image_header_t' has no member named 'reserved'
eBoot/include/eos_image.h:142: error: ...

None of those PRs touches eBoot. Every one of them is carrying a red X that
belongs here.

Reproduced locally, both directions

The failure is a _Static_assert in a header, so it needs no ARM toolchain —
any compiler that parses eos_image.h hits it. Compiling a two-line
translation unit that does nothing but include the header:

eBoot master : FAILS
    eos_image.h:135:23: error: no member named 'reserved' in 'eos_image_header_t'
    eos_image.h:142:57: error: no member named 'reserved' in 'eos_image_header_t'
    2 errors generated.
eBoot #94    : COMPILES CLEAN

So the fix in this PR is exactly the fix for the eos-side failure, and I can
confirm that without waiting for CI to tell us.

Why it happened, for the record

master asserts offsetof(eos_image_header_t, reserved) == 62 against a struct
that no longer has a reserved member — the TLV work replaced those 30 bytes
and the assert pinning them was left behind. A static assert on a field that
does not exist is not a weakened check; it is a header that cannot be included
at all, which is why it takes out every consumer rather than one test.

Ask

Nothing to change here — this PR is MERGEABLE, its own checks are green
(4 pass, 2 skipped), and I have verified it fixes the defect. Landing it
clears one red X from eleven eos PRs in one merge
, which is a better return
than anything else currently queued.

If it helps triage: the only other recurring red on those eos PRs is the
test_crypto_ed25519_loworder registration, which #127 in eos fixes. Between
this and eos#127, the eos queue goes green.

Kartikey1306 added a commit to Kartikey1306/eBoot that referenced this pull request Sep 3, 2026
Rebuilt from the review on cf4bf4f. The FDT work is unchanged; everything
else in this branch is a response to a finding.

Finding 3 -- scope. core/ed25519_verify.c, include/eos_image.h and
tests/unit/test_ed25519.c are gone from this branch. They were a master
repair, and embeddedos-org#94 owns it. The branch is now stacked on embeddedos-org#94 rather than racing
it; git dropped the duplicate as "patch contents already upstream", which is
the confirmation that all three PRs were carrying the same fix.

Finding 1 -- the Fuzz Harness Build job this PR adds was red, and it was red
for a reason worth stating plainly: three of the five harnesses call functions
that have never existed anywhere in the tree.

  fuzz_fw_update.c          eos_fw_update_init, _process_chunk   -- no such symbols
  fuzz_recovery_protocol.c  eos_recovery_parse_packet            -- no such symbol
  fuzz_bootctl.c            eos_bootctl_parse                    -- no such symbol

Deleted, with their add_executable blocks. Each declared its target with a
local extern instead of including a header, so nothing ever checked that the
function existed; and the job that would have caught it did not exist until
this PR added it. Deleting a harness that has never compiled removes no
coverage -- but it does remove the appearance of coverage, which is finding 2
and is the part that matters. eBoot has no fuzz coverage of firmware-update
stream parsing or the recovery protocol, and now says so.

fuzz_image_verify.c was worse than dead: it linked. It declared

    extern int eos_image_parse_header(const void *flash_base, size_t flash_len);

against a function that is (uint32_t addr, eos_image_header_t *out), so it
passed a pointer as a flash address and a size_t as an output-struct pointer.
C does not check a declaration against a definition in another translation
unit, so it built, ran, and fuzzed nothing. It now includes eos_image.h --
which is what makes the compiler check the call -- and drives the real parser
through a flash backend registered with eos_hal_init(), the seam
tests/unit/test_image_verify.c already uses.

Finding 4 -- the "-8 the node path is deeper than FDT_MAX_PATH_DEPTH" line is
gone from include/eos_fdt_loader.h. No path returned it and the constant is
defined nowhere.

Findings 5 and 6 -- the two fuzz_fdt.c comments now say what is true. The
`size` justification no longer argues against unsized entry points this PR
removed, and "/chosen" is described as the not-found probe it is until embeddedos-org#85
lands, rather than as coverage of the match path.

Finding 7 is moot: the ed25519 comment rewrite that dropped the eBoot#57
attribution is no longer part of this branch.

Verified: ctest 22/22, and 22/22 again under -DEBLDR_SANITIZE=ON. All three
surviving harnesses link and run against a stub driver (no libFuzzer on this
machine, so the smoke-run step is checked in CI, not here).
@Kartikey1306

Copy link
Copy Markdown
Contributor Author

Root cause identified, and it is my own merged PR. Owning it plainly since it
changes how urgent this is.

Which commit broke master, and how

abd4dab  Fix/authenticate tlv anti rollback (#93)      <- removed uint8_t reserved[30]
bbd997a  fix(image): pin the whole .efw header (#87)   <- added offsetof(..., reserved) asserts

Bisecting the header across master's recent commits:

v3.0.1    eos_image.h errors: 0
abd4dab   eos_image.h errors: 0
bbd997a   eos_image.h errors: 2   <- breaks here
32723b3   eos_image.h errors: 2
22d8f8b   eos_image.h errors: 2   (current master)

#93 replaced reserved[30] with the TLV fields. #87 — mine — was written
against a base where reserved still existed, merged after #93, and added

EOS_IMG_STATIC_ASSERT(offsetof(eos_image_header_t, reserved) == 62, ...);
EOS_IMG_STATIC_ASSERT(sizeof(((eos_image_header_t *)0)->reserved) == 30, ...);

against a member that was no longer there. Both PRs were individually green;
neither was rebuilt against the other before landing. That is the exact
failure mode #92 and #87-the-issue describe, and I produced an instance of it
while arguing for the gate that would have caught it.

Confirmed this PR is the complete fix

Full build, not just the header:

eBoot #94   : configure OK, build errors 0, ctest 21/21
eBoot master: build errors 10

Why it is worth merging ahead of the queue

eos's eos-simulation.yml checks out embeddedos-org/eBoot@master and
cross-builds it, so this breakage fails Cross-compile ARM64 kernel on every
open eos pull request
. Currently red for this reason:

eos #114 #115 #116 #117 #118 #119 #121 #122 #127 #129 #134

Eleven PRs, none of which touch eBoot. Merging this clears all eleven.

Separate observation, not a proposal for this PR

That coupling is worth revisiting on its own: pointing PR CI at another
repository's moving default branch means their breakage blocks your merges and
you cannot fix it from your side. Pinning the integration build to a release
tag for pull requests, and keeping a scheduled run against master so drift is
still caught loudly, would decouple them without going fail-open. I am
deliberately not folding that into this PR — it would look like routing
around my own breakage rather than fixing it, and this PR should stay the
minimal repair.

@Kartikey1306

Copy link
Copy Markdown
Contributor Author

Evidence for prioritizing this: merging it takes 12 currently-red eos PRs green in one step, with no change needed on any of them.

Every open eos PR fails exactly one job — EoS Full-Stack Simulation — because eos's workflow builds eBoot@master, and master does not compile. Verified locally rather than inferred, under that job's own configuration (-DEBLDR_BOARD=qemu_arm64 -DEBLDR_VERIFY_STAGE1=OFF -DCMAKE_BUILD_TYPE=Release, cross-compile mode):

ref result
master (22d8f8b) fails — eos_image.h:135/:142: offsetof(eos_image_header_t, reserved) for a member that became tlv_len + tlv_hash
this PR's head builds every target, rc=0, and its suite is 21/21

Master carries a second, independent break this PR also fixes: point_is_identity redefined in core/ed25519_verify.c — it entered when #57 merged on top of #86's near-identical hardening. Walking master back and building each candidate, the newest compiling ancestor is a172a6d (its child 8a015b2 already fails).

Both defects are pairs of PRs that merged clean and broke the build together; eos PR #135 pins eos's eBoot checkout to a172a6d so the next such pair cannot redden every eos PR again, and its own simulation run is green on that pin. Once this merges, that pin bumps to this merge SHA.

Since eos PR CI runs on the merge commit with master, the 12 eos PRs go green on their next run after this lands — no rebases, no pushes.

@srpatcha
srpatcha merged commit c36b3e7 into embeddedos-org:master Sep 8, 2026
27 checks passed
srpatcha pushed a commit that referenced this pull request Sep 8, 2026
* fix: repair master — the ABI asserts and the Ed25519 verifier both merged broken

master (22d8f8b) does not compile. Two independent double-merges, both the
same shape: two PRs fixing adjacent things landed on stale bases, each was
green on its own branch, and the result was never rebuilt.

1. include/eos_image.h — #93 replaced reserved[30] with tlv_len (2) +
   tlv_hash[28], preserving every offset. #87 merged afterwards carrying
   asserts written against the older struct:

     error: no member named 'reserved' in 'eos_image_header_t'   (x2)

   #93 already asserts tlv_len at 62 and tlv_hash at 64, so the offset assert
   was a duplicate; the width assert had no replacement and is restored as two
   asserts covering both halves of the same 30-byte span. No offset moves and
   the wire format is unchanged.

2. core/ed25519_verify.c — #86 and #57 both landed a subgroup guard, so the
   file carried two byte-identical point_is_identity() definitions:

     error: redefinition of 'point_is_identity'

   Only #57's public_key_is_valid_subgroup() is wired to the call site, so
   #86's key_has_prime_order() was dead. Kept the live function, folded #86's
   fuller rationale onto it, deleted the duplicate.

3. tests/unit/test_ed25519.c — collateral from the same merge. Two copies of
   test_ed25519_identity_key_forgery_rejected, main() calling it twice and two
   tests not at all, and test_ed25519_low_order_R_with_a_valid_key_is_not_a_forgery
   referencing k_low_order[] and messages[] that the merge had dropped.

   While restoring the corpus, corrected it (review finding on #86): the array
   claimed to hold "the eight low-order point encodings" and held five. Every
   order here was computed rather than copied — decode y, recover x, add the
   point to itself until it reaches the identity — giving 1, 2, 4, 4, 8, 8, 8,
   8. Missing before: y=0 with the sign bit set, and both sign-flipped order-8
   encodings. D9FF..FF was in the array and is not a low-order point at all —
   no x satisfies the curve equation for that y — so it moves to a separate
   k_non_canonical[], with EDFF..FF7F (y=p) and EEFF..FF7F (y=p+1).

   tests_run was assigned a literal (11) in main() and never incremented,
   which is how the duplicate call and the two unregistered tests went
   unnoticed. The TEST macro now increments it, so the total cannot drift.

Verified:
  cmake -DEBLDR_BUILD_TESTS=ON on master   FAILS to build, 3 errors
  same with this commit                    builds clean
  ctest                                    21/21 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   21/21 PASS
  pytest tests/                            24 passed, 1 skipped
  test_ed25519                             14/14 PASS (was 11 claimed, 12 run)
  discrimination, with `public_key_is_valid_subgroup` disabled:
    test_ed25519_low_order_keys_rejected   FAILS, as it must
    test_ed25519_non_canonical_...         still PASSES — those are refused by
      unpackneg() on canonicality, a different mechanism, which is the reason
      they are held in a separate array rather than counted among the eight.

* fix(fuzz): point every harness at the API it claims to fuzz

Four of the five fuzz harnesses did not test what they name, and the
build could not say so because not one of them includes a project
header. Each declares its target itself:

  fuzz_recovery_protocol.c  extern int eos_recovery_parse_packet(...)
  fuzz_fw_update.c          extern int eos_fw_update_init(void)
                            extern int eos_fw_update_process_chunk(...)
                            extern int eos_fw_update_finalize(void)
  fuzz_bootctl.c            extern int eos_bootctl_parse(...)
  fuzz_image_verify.c       extern int eos_image_parse_header(const void *, size_t)

eos_recovery_parse_packet, eos_fw_update_init,
eos_fw_update_process_chunk and eos_bootctl_parse have never existed —
those names appear nowhere outside the harness that declares them, so
three of the five targets have never linked.

The other two are worse, because they do link:

  - eos_fw_update_finalize exists but takes (ctx, mode), not (void).
  - eos_image_parse_header takes (uint32_t addr, eos_image_header_t *),
    not (const void *, size_t). fuzz_image_verify has been passing a
    pointer where an address is expected and a length where an output
    struct is expected, on every input, for as long as it has run.

A local extern is why none of this was caught: it tells the compiler the
symbol exists with whatever shape the harness asserts, and the mismatch
survives to link time or past it.

All five now include the real header and drive the real entry points:

  fuzz_image_verify       parse_header -> verify_integrity, boot-path order
  fuzz_bootctl            bootctl_load, then trap if load() accepted a
                          block validate() rejects
  fuzz_fw_update          begin -> write in fuzz-chosen chunk widths ->
                          finalize or abort
  fuzz_recovery_protocol  write_in_range, trapping on any accepted write
                          that leaves the slot or wraps, checked in wider
                          types that cannot
  fuzz_crypto             already correct; switched to the header so it
                          stays that way

Adds tests/fuzz/fuzz_sim_flash.h: the three harnesses that reach flash
need board ops installed, and without them they fuzz a null op table.

That the compiler now checks this is not theoretical — writing this, it
rejected EOS_UPGRADE_MODE_TEST for EOS_UPGRADE_TEST immediately, which
is exactly the error class the externs were hiding.

Verified. libFuzzer is unavailable here (libclang_rt.fuzzer_osx.a not
found), so each harness was linked against eboot_core and driven by a
standalone seed generator under ASan+UBSan:

  all five compile -Wall -Wextra    5/5, 0 failures
  20,000 inputs each               100,000 total, no reports
  ctest                            21/21 passed

Third instance of this class across these repos, after eos#50
(fuzz_devicetree naming eos_dtb_parse) and eos#110 (fuzz_ota_header
naming eos_ota_parse_header). The common factor every time is a fuzz
target declaring its own subject.

Stacked on #94, without which include/eos_image.h does not compile.

* fix(fuzz): the recovery oracle was off by one, and CI proved it

The restored Fuzz Harness Build job on #101 ran these harnesses under
real libFuzzer for the first time and fuzz_recovery_protocol trapped
within seconds. That was my bug, not the code's.

The oracle computed the one-past-the-end address:

    end = base + offset + len;  if (end > 0xFFFFFFFF) trap;

The last byte a write of len bytes touches is base + offset + len - 1.
eos_recovery_write_in_range() checks exactly that:

    if ((uint32_t)len - 1u > UINT32_MAX - (base + offset)) reject;

So an accepted write whose final byte lands exactly on 0xFFFFFFFF --
base=0xFFFFFF00, offset=0, len=256 -- is legal, the function accepts it,
and the old oracle trapped on it. A harness that traps on valid input
reports the opposite of the truth.

Verified both directions:
  the boundary case, fed directly      -> no trap
  a fail-open stub accepting all input -> trap fires (exit 133)
  500,000 random inputs, ASan+UBSan    -> no reports

libFuzzer doing precisely what it is for -- driving inputs into the one
corner a hand-written oracle got wrong -- is the strongest argument yet
for #101's job. The guard could never have caught this; only execution
under a coverage-driven fuzzer did.
srpatcha added a commit that referenced this pull request Sep 8, 2026
* fix: repair master — the ABI asserts and the Ed25519 verifier both merged broken

master (22d8f8b) does not compile. Two independent double-merges, both the
same shape: two PRs fixing adjacent things landed on stale bases, each was
green on its own branch, and the result was never rebuilt.

1. include/eos_image.h — #93 replaced reserved[30] with tlv_len (2) +
   tlv_hash[28], preserving every offset. #87 merged afterwards carrying
   asserts written against the older struct:

     error: no member named 'reserved' in 'eos_image_header_t'   (x2)

   #93 already asserts tlv_len at 62 and tlv_hash at 64, so the offset assert
   was a duplicate; the width assert had no replacement and is restored as two
   asserts covering both halves of the same 30-byte span. No offset moves and
   the wire format is unchanged.

2. core/ed25519_verify.c — #86 and #57 both landed a subgroup guard, so the
   file carried two byte-identical point_is_identity() definitions:

     error: redefinition of 'point_is_identity'

   Only #57's public_key_is_valid_subgroup() is wired to the call site, so
   #86's key_has_prime_order() was dead. Kept the live function, folded #86's
   fuller rationale onto it, deleted the duplicate.

3. tests/unit/test_ed25519.c — collateral from the same merge. Two copies of
   test_ed25519_identity_key_forgery_rejected, main() calling it twice and two
   tests not at all, and test_ed25519_low_order_R_with_a_valid_key_is_not_a_forgery
   referencing k_low_order[] and messages[] that the merge had dropped.

   While restoring the corpus, corrected it (review finding on #86): the array
   claimed to hold "the eight low-order point encodings" and held five. Every
   order here was computed rather than copied — decode y, recover x, add the
   point to itself until it reaches the identity — giving 1, 2, 4, 4, 8, 8, 8,
   8. Missing before: y=0 with the sign bit set, and both sign-flipped order-8
   encodings. D9FF..FF was in the array and is not a low-order point at all —
   no x satisfies the curve equation for that y — so it moves to a separate
   k_non_canonical[], with EDFF..FF7F (y=p) and EEFF..FF7F (y=p+1).

   tests_run was assigned a literal (11) in main() and never incremented,
   which is how the duplicate call and the two unregistered tests went
   unnoticed. The TEST macro now increments it, so the total cannot drift.

Verified:
  cmake -DEBLDR_BUILD_TESTS=ON on master   FAILS to build, 3 errors
  same with this commit                    builds clean
  ctest                                    21/21 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   21/21 PASS
  pytest tests/                            24 passed, 1 skipped
  test_ed25519                             14/14 PASS (was 11 claimed, 12 run)
  discrimination, with `public_key_is_valid_subgroup` disabled:
    test_ed25519_low_order_keys_rejected   FAILS, as it must
    test_ed25519_non_canonical_...         still PASSES — those are refused by
      unpackneg() on canonicality, a different mechanism, which is the reason
      they are held in a separate array rather than counted among the eight.

* fix(fdt): bound a device tree parser that was never compiled

core/fdt_loader.c is in no source list, so it has never been built. The
header offers it to callers, rtos_boot.c is named as the consumer, and
nothing catches what is in it -- not the compiler, not ctest, not the
sanitizer job.

What is in it is a parser for a blob that comes out of flash, whose every
header field it uses as an offset or a length without checking any of
them. eos_fdt_validate() looks at magic and version only, so it accepts
a blob whose off_dt_struct points anywhere:

    hdr.totalsize     = 40      (the header alone)
    hdr.off_dt_struct = 0x100000
    eos_fdt_validate(blob) -> 0
    eos_fdt_get_prop(...)  -> AddressSanitizer: BUS, READ at
                              fdt_loader.c:25 in fdt_read_u32

Five more, all reachable the same way:

* the tag read at the top of the loop takes 4 bytes where the loop
  condition guarantees 1;
* strlen() on a node name reads until it finds a zero, which for a name
  running to the end of the block is past it;
* nameoff indexes the strings block unchecked, so strcmp() reads from an
  arbitrary address;
* a property len is clamped to the caller's buffer before the memcpy,
  which bounds the write but not the read -- an oversized len copies
  whatever follows the blob out to the caller;
* FDT_END_NODE decrements depth with no floor.

Bound them. validate() is the gate every path goes through, so the block
offsets are checked against totalsize there, and get_prop() calls it
before trusting the header. Inside the loop each read is checked for the
width it takes, the name and property-name scans are bounded by memchr
within their blocks, and the padded advances are re-checked for overrun.

Adds the file to eboot_core and tests/unit/test_fdt_loader.c to ctest:
ten cases, one well-formed tree that must still parse and nine malformed
ones. Against the unfixed parser the suite fails on the third; with the
bounds in place the whole suite is 20/20, and 20/20 under EBLDR_SANITIZE.

Not fixed here, because it is a behaviour change rather than a safety
one: node paths below the root do not resolve. _get_prop derives the
depth to match from a slash count, so "/chosen" looks for depth 1, which
is the root -- "chosen" is at depth 2. Only "/" resolves today.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(fdt): bound the parser against the caller's length, not the blob's claim

Follow-up to the review on #84. Three findings from it, all in files this
branch already owns.

Finding 1 (High) -- every bound in eos_fdt_validate() was expressed relative
to hdr->totalsize, which is read out of the same untrusted blob. Checking the
block offsets against it proves the header is internally consistent and says
nothing about how many bytes are really mapped: a 40-byte buffer declaring
totalsize = 0x100000 with agreeing offsets passed every check, and
eos_fdt_get_prop() then walked a megabyte past the allocation. The original
reproducer (an inflated *offset* against an honest totalsize) was rejected;
its mirror image was not.

Adds the length-carrying entry points eos_fdt_validate_sized() and
eos_fdt_get_prop_sized(), which take the bytes the caller actually owns and
check totalsize against that before anything else. The existing two-argument
forms stay as wrappers that trust the blob's own totalsize, documented in the
header as a warrant the caller has to make good; eos_fdt_load() now passes
max_size, which it had all along.

Finding 2 (Medium) -- a property larger than the caller's buffer was copied
short and reported as success, so a clipped value was indistinguishable from
a complete one. In a boot path this reads bootargs. Now returns -7 and sets
*buf_len to the full length so the caller can size a retry.

Finding 3 (Medium) -- adds tests/fuzz/fuzz_fdt.c alongside the five existing
harnesses. .ai/security.md names device tree among the parsers that get fuzz
coverage rather than unit tests alone. It drives the sized entry points and
passes the real size, which is what makes the harness meaningful -- the
unsized forms would let a fuzzer authorise its own out-of-bounds read.

Finding 6 (Low) -- drops the unreachable `total < sizeof(fdt_header_t)` check
in eos_fdt_load(); validate() already rejects that blob, and the comment
above it described a bound it was not applying.

Header now documents the full -1..-8 return code table.

Verified:
  cmake -DEBLDR_BUILD_TESTS=ON, ctest              21/21 PASS
  same under -DEBLDR_SANITIZE=ON (ASan+UBSan)      21/21 PASS
  test_fdt_loader                                  14 tests PASS (was 10)
  new tests against the pre-fix parser             both FAIL as they should
    - inflated totalsize accepted at the sized entry point
    - truncating call returned 0 instead of -7
  grep for eos_fdt_get_prop / eos_fdt_validate     no callers outside the
    parser and its tests, so the -7 change breaks nothing today

Refs #84

* fix(build): drop the duplicate core/fdt_loader.c registration

master gained core/fdt_loader.c in eboot_core while this branch was open, so
after the rebase it appeared twice and
tests/unit/test_cmake_core_sources.py::test_core_sources_are_registered_once
failed:

    AssertionError: ['core/fdt_loader.c'] is not false :
    duplicate eboot_core sources: ['core/fdt_loader.c']

Kept master's entry, dropped the one this branch added. That guard is the
same shape as the one this stack adds for toolchain specs -- a build-file
check that catches the class rather than the instance -- and it did its job.

Verified: ctest 22/22 PASS, pytest 24 passed 1 skipped.

Refs #84

* fix(fdt): one length-carrying API, and a CI job that builds the fuzz harnesses

Answers the second review on #84.

Finding 2 (Medium) -- eos_fdt_validate() and eos_fdt_get_prop() kept an
out-of-bounds read by design. Both dereferenced hdr->totalsize before any
length was known and handed that attacker-controlled value to the _sized form
as its bound, so calling either on a short buffer read past it before a single
check had run. The header called that a caller warrant; a warrant is not a
check, and it is the exact bug this PR exists to fix. Neither had an in-tree
caller.

Removed rather than documented. There is now one form of each entry point and
it always takes the length:

    int eos_fdt_validate(const void *fdt_blob, uint32_t avail);
    int eos_fdt_get_prop(const void *fdt, uint32_t fdt_len, ...);

An exported unsafe twin in a TCB header is a future boot-path caller
reintroducing the bug with no compiler complaint, which is worth more than the
convenience of a one-argument call. eos_fdt_load() already passed max_size.
The test that pinned the wrapper's behaviour is gone with the wrapper, and
get_prop_sized_exact() collapsed into get_prop_exact() since they became the
same function.

Finding 3 (Medium) -- tests/fuzz/ was built by nothing. EBLDR_BUILD_FUZZ
defaults OFF and no job set it, so the harness added here joined five others
that no CI job compiles. A harness that is never built cannot fail to build,
which is how fuzz_devicetree came to declare a function that did not exist and
sit there unnoticed (eos#50).

Adds a `fuzz-build` job: configure with clang, build every harness, and run
each for five seconds over its own generated inputs. That is not a campaign --
it is enough to catch a harness that no longer compiles or crashes at once,
which is the failure this repo has actually had. Note it needs
EBLDR_BUILD_TESTS=ON as well: tests/fuzz/ is added from tests/CMakeLists.txt,
so EBLDR_BUILD_FUZZ alone configures cleanly and builds no harness at all --
the job would have passed having compiled nothing. Found that locally before
writing the job, not after.

  NOT RUN, and this is the honest limit: this host has no libFuzzer runtime
  (libclang_rt.fuzzer_osx.a is absent from the Xcode toolchain), so the link
  step cannot be reproduced here for any harness, old or new. What I verified
  is that CMake configures with both flags and reports all six targets --
  "Fuzz targets: fuzz_image_verify, fuzz_recovery_protocol, fuzz_fw_update,
  fuzz_crypto, fuzz_bootctl, fuzz_fdt" -- and that fuzz_fdt.c passes
  `cc -fsyntax-only`. The link and the smoke run are CI's to show, and this
  job is what makes them visible.

  Coordination note: #90 adds a `CI Gate` whose needs list is
  [test, build-arm, static-analysis]. Whichever of #84 and #90 lands second
  must add fuzz-build to that list -- and #90's own
  test_gate_covers_every_job_that_runs_on_a_pull_request fails loudly if it is
  not, which is the guard working rather than a trap.

Finding 1 (High) is a PR-body correction, made there: the diff carries #94's
master repair because this branch is stacked on it, and the body described
only the FDT parser.

Verified:
  ctest                                    22/22 PASS
  pytest tests/                            38 passed
  test_fdt_loader                          13 tests PASS
  grep for a length-free entry point       none remains in the header

Refs #84

* ci: move the fuzz-harness build to its own PR

The fuzz-build job added in the previous commit does its job -- it is red, on
harnesses this PR did not write:

    undefined reference to `eos_fw_update_init'
    undefined reference to `eos_fw_update_process_chunk'
    undefined reference to `eos_recovery_parse_packet'

None of those exist anywhere in the tree. tests/fuzz/fuzz_fw_update.c and
fuzz_recovery_protocol.c declare an API that was never written, exactly as
eos#50's fuzz_devicetree declared eos_dtb_parse(). They have compiled forever
because nothing ever linked them.

That is a real finding and it deserves a fix, not a red tick on an unrelated
PR. The job and the repairs move to their own change; this PR keeps
tests/fuzz/fuzz_fdt.c, which is the harness it is responsible for.

Refs #84

* fix(fdt): read the header the way the struct block is read, and stop resynchronising on garbage

Answers the third review on #84.

Finding 3 (Low, and the one that matters on hardware) -- the header was read
through a cast fdt_header_t* and direct member loads, while every struct-block
read goes through the fdt_read_u32() memcpy helper precisely because the blob
may be unaligned. Fuzz input, a buffer inside a larger message, a copy at an
odd offset: nothing promises 4-byte alignment, and on a strict-alignment
cross target a direct member load is the same fault class this parser exists
to avoid. The unit suite could never catch it -- blob_t.bytes happens to be
aligned.

All header fields now go through fdt_hdr_u32() (memcpy at offsetof), one rule
for the whole blob, in validate(), load() and get_prop(). FUZZ_FLAGS gains
`undefined` so the fuzz job checks alignment too.

Finding 4 (Low) -- `default: break;` resynchronised on unrecognised tags: the
walk skipped 4 bytes and treated whatever followed as the next token, so a
struct block of arbitrary bytes parsed to a clean "not found". Bounded, but a
TCB parser that walks garbage to completion is accepting input it does not
understand. FDT_NOP -- the one legal unknown, padding the spec allows between
tokens -- is now named in the header and passes; anything else returns -6.

Findings 1, 2 and the -8 line: the fuzz-build job's single home is #101
(nothing added here; the harness is inert until that job lands and then
compiled by it -- said on the thread, not just here), and the header no longer
documents return code -8, which nothing at this head returns. #85 adds the -8
return and re-documents it together with the FDT_MAX_PATH_DEPTH move.

Verified:
  ctest                                    22/22 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   22/22 PASS
  pytest tests/                            38 passed
  test_fdt_loader                          16 tests PASS (was 13)
  discrimination, each fix in isolation:
    default: break restored     -> test_a_garbage_tag_is_refused_not_skipped
                                   FAILS (expects -6, gets "not found")
    direct member load restored -> under UBSan the new unaligned-blob test
                                   reports "load of misaligned address
                                   0x...671 for type 'const uint32_t'" at the
                                   exact line -- and cannot fire on the fixed
                                   code, which runs the same test clean
  NOP counter-check: interleaved FDT_NOP tokens still resolve, so the
  stricter default does not reject real trees.

Refs #84

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Srikanth Patchava <srikanth.patchava@outlook.com>
srpatcha pushed a commit that referenced this pull request Sep 8, 2026
…ul boot (#82)

* fix: repair master — the ABI asserts and the Ed25519 verifier both merged broken

master (22d8f8b) does not compile. Two independent double-merges, both the
same shape: two PRs fixing adjacent things landed on stale bases, each was
green on its own branch, and the result was never rebuilt.

1. include/eos_image.h — #93 replaced reserved[30] with tlv_len (2) +
   tlv_hash[28], preserving every offset. #87 merged afterwards carrying
   asserts written against the older struct:

     error: no member named 'reserved' in 'eos_image_header_t'   (x2)

   #93 already asserts tlv_len at 62 and tlv_hash at 64, so the offset assert
   was a duplicate; the width assert had no replacement and is restored as two
   asserts covering both halves of the same 30-byte span. No offset moves and
   the wire format is unchanged.

2. core/ed25519_verify.c — #86 and #57 both landed a subgroup guard, so the
   file carried two byte-identical point_is_identity() definitions:

     error: redefinition of 'point_is_identity'

   Only #57's public_key_is_valid_subgroup() is wired to the call site, so
   #86's key_has_prime_order() was dead. Kept the live function, folded #86's
   fuller rationale onto it, deleted the duplicate.

3. tests/unit/test_ed25519.c — collateral from the same merge. Two copies of
   test_ed25519_identity_key_forgery_rejected, main() calling it twice and two
   tests not at all, and test_ed25519_low_order_R_with_a_valid_key_is_not_a_forgery
   referencing k_low_order[] and messages[] that the merge had dropped.

   While restoring the corpus, corrected it (review finding on #86): the array
   claimed to hold "the eight low-order point encodings" and held five. Every
   order here was computed rather than copied — decode y, recover x, add the
   point to itself until it reaches the identity — giving 1, 2, 4, 4, 8, 8, 8,
   8. Missing before: y=0 with the sign bit set, and both sign-flipped order-8
   encodings. D9FF..FF was in the array and is not a low-order point at all —
   no x satisfies the curve equation for that y — so it moves to a separate
   k_non_canonical[], with EDFF..FF7F (y=p) and EEFF..FF7F (y=p+1).

   tests_run was assigned a literal (11) in main() and never incremented,
   which is how the duplicate call and the two unregistered tests went
   unnoticed. The TEST macro now increments it, so the total cannot drift.

Verified:
  cmake -DEBLDR_BUILD_TESTS=ON on master   FAILS to build, 3 errors
  same with this commit                    builds clean
  ctest                                    21/21 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   21/21 PASS
  pytest tests/                            24 passed, 1 skipped
  test_ed25519                             14/14 PASS (was 11 claimed, 12 run)
  discrimination, with `public_key_is_valid_subgroup` disabled:
    test_ed25519_low_order_keys_rejected   FAILS, as it must
    test_ed25519_non_canonical_...         still PASSES — those are refused by
      unpackneg() on canonicality, a different mechanism, which is the reason
      they are held in a separate array rather than counted among the eight.

* fix(secure-boot): a debug lock that failed must not report a successful boot

cfg.lock_debug asks for SWD/JTAG to be closed before the verified image runs.
Step 7 of eos_secure_boot() honoured that request like this:

    if (cfg->lock_debug) {
        eos_secure_boot_lock_debug();
    }

    /* ---- Step 8: Record successful attestation ---- */
    attest_record(2, hdr.image_version, hdr.hash, NULL, EOS_SBOOT_OK);
    return EOS_SBOOT_OK;

eos_secure_boot_lock_debug() returned void and discarded the result of the OTP
write that actually blows the fuse. So when the write failed, boot continued,
attestation recorded EOS_SBOOT_OK, and the device ran the image with its debug
port open -- the exact condition the policy existed to prevent, reported as a
clean secure boot.

The interesting case is not a flaky fuse. eos_hal_otp_write() returns
EOS_ERR_NOT_SUPPORTED when the board provides no otp_write hook at all, so on
every such board `lock_debug: true` was silently a no-op. That is the default
configuration, not an edge case.

eos_secure_boot_lock_debug() now returns int, and a caller that asked for the
lock and did not get it fails with EOS_SBOOT_ERR_POLICY -- a code that already
existed for exactly this ("Boot policy violation") -- with the failure recorded
in the attestation log rather than a success.

Why this was never observable: core/secure_boot.c is not in CMakeLists.txt.
The module has never been compiled, so this path could not run and could not be
tested. Added the one line that builds it -- the same line #72 adds, written
identically so whichever lands first leaves the other a trivial rebase.

tests/unit/test_secure_boot_policy.c covers the three outcomes: the fuse
written, the write failing, and a board with no otp_write. Kept in its own file
so it does not collide with the test_secure_boot.c #72 introduces.

Against master the new test does not compile -- `invalid operands to binary
expression ('void' and 'int')` -- because there is no result to check. That is
the defect stated as a compile error.

Verified on this branch: build clean, ctest 20/20, pytest 30 passed.

Stacked on #77 (master's test suite does not compile without it).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(secure-boot): test the policy the PR changed, not only the helper it calls

Answers finding 1 (Medium) from the review on #82.

All three tests called eos_secure_boot_lock_debug() directly and asserted its
return value. None drove eos_secure_boot() with cfg.lock_debug = true, so the
step-7 early return this PR adds -- the attest_record + return
EOS_SBOOT_ERR_POLICY -- never executed under test. The file's docblock says
"the debug-lock policy must be enforced, not merely attempted"; what it
covered was the attempted half.

Adds three end-to-end cases through eos_secure_boot():

  - lock_debug: true on a board with no otp_write  -> EOS_SBOOT_ERR_POLICY
  - the same image with lock_debug: false          -> EOS_SBOOT_OK, and the
    recorded entry point is the header's, which is the counter-check: without
    it the first test would also pass if steps 1-6 were failing for an
    unrelated reason and never reaching step 7
  - lock_debug: true with a working fuse           -> EOS_SBOOT_OK, one write

Reaching step 7 needs an image that clears steps 1, 2 and 5, so the fixture
gains a simulated flash and stages an unsigned, unencrypted image whose
SHA-256 matches. EOS_IMG_FLAG_HASH_SHA256 is load-bearing there: without it
verify_integrity takes the CRC32 branch, reads a CRC out of hash[], and
step 2 fails before the policy step is ever reached.

Finding 4 (Low), the tests/CMakeLists.txt anchor shared with #80, is resolved
on #80's side -- its block moved to the end of the registrations, so this one
keeps its position and the two no longer collide.

Verified:
  ctest                                  22/22 PASS
  test_secure_boot_policy                6/6 PASS
  discrimination: with step 7 reverted to `(void)eos_secure_boot_lock_debug();`
    test_secure_boot_refuses_when_the_debug_lock_cannot_be_taken  FAILS
    the three original helper tests                               still PASS
  which is the gap the finding described, reproduced.

Refs #82

* fix(secure-boot): step 4 must not report success for a check it never makes

Answers the second review on #82.

Finding 1 (High) -- step 4, "Verify signing key against OTP root-of-trust",
was the same fail-open this PR removes from step 7, two steps earlier. An
`eos_hal_otp_read()` failure was discarded and boot continued; and when the
read succeeded and the anchor was provisioned, the body of the `if` was
`/* In a full implementation, extract key hash from TLV and compare */`. So a
device whose root of trust *is* provisioned booted an image signed by any key
the image carried, and step 8 recorded EOS_SBOOT_OK.

Implementing the TLV comparison is out of scope, as the review says. The two
things that are in scope are done: a non-EOS_OK otp_read now fails
EOS_SBOOT_ERR_SIGNATURE, and a provisioned anchor that nothing compares
against refuses the boot rather than proceeding. An unprovisioned board
(all-zero anchor) is deliberately unchanged -- there is nothing to check
against, and refusing would brick every board that has not been provisioned.
The comment now states plainly that the step is planned rather than
implemented, which §8.1 asks for and a comment inside an `if` was not.

  No test for those two refusals, deliberately, and the file says why rather
  than leaving it to be discovered. Reaching step 4 requires passing step 3 --
  a real Ed25519 signature checked against the keystore. I wrote the obvious
  test first and it was worthless: with require_signature = true and an
  unsigned fixture the boot fails at step 3 and returns the same
  EOS_SBOOT_ERR_SIGNATURE step 4 returns, so it passed against the unfixed
  code too. I confirmed that by reverting step 4 and watching it still pass.
  A test that cannot fail is worse than none. What is there instead is the
  counter-check that the change does not refuse a boot it should allow.

  The fixture is buildable -- the keystore ships RFC 8032 TEST 1's public key
  and the matching private key is in the RFC -- but that machinery is #88's
  (tools/gen_signed_image_fixture.py). Worth doing once #88 lands.

Finding 3 (Low) -- `TEST()` did not increment `tests_run` and `main()`
hardcoded `tests_run = 6`, so a test added to the file but not wired into
`main()` would have been skipped with a zero exit. #94 removed exactly this
from tests/unit/test_ed25519.c, where a hardcoded 11 was masking two uncalled
tests. Same fix here.

Finding 4 (Low) -- the Valgrind `foreach` is hand-maintained and missed 6 of
22 registered tests. Added test_secure_boot_policy, test_fdt_loader and
test_fw_decrypt. The list being hand-maintained at all is the real defect and
is not fixed here -- it is the same class as the hardcoded count, one level
up.

Finding 2 (Medium), that eos_secure_boot() has no production caller, stands
and is not addressed here; finding 1 makes it sharper rather than resolving
it. Finding 5 (Low) is a PR-body correction.

Verified:
  ctest                          22/22 PASS
  test_secure_boot_policy        7/7 PASS
  step 7 discrimination, still: reverting the step-7 branch fails
    test_secure_boot_refuses_when_the_debug_lock_cannot_be_taken

Refs #82

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
srpatcha added a commit that referenced this pull request Sep 8, 2026
…ing them (#95)

* fix: repair master — the ABI asserts and the Ed25519 verifier both merged broken

master (22d8f8b) does not compile. Two independent double-merges, both the
same shape: two PRs fixing adjacent things landed on stale bases, each was
green on its own branch, and the result was never rebuilt.

1. include/eos_image.h — #93 replaced reserved[30] with tlv_len (2) +
   tlv_hash[28], preserving every offset. #87 merged afterwards carrying
   asserts written against the older struct:

     error: no member named 'reserved' in 'eos_image_header_t'   (x2)

   #93 already asserts tlv_len at 62 and tlv_hash at 64, so the offset assert
   was a duplicate; the width assert had no replacement and is restored as two
   asserts covering both halves of the same 30-byte span. No offset moves and
   the wire format is unchanged.

2. core/ed25519_verify.c — #86 and #57 both landed a subgroup guard, so the
   file carried two byte-identical point_is_identity() definitions:

     error: redefinition of 'point_is_identity'

   Only #57's public_key_is_valid_subgroup() is wired to the call site, so
   #86's key_has_prime_order() was dead. Kept the live function, folded #86's
   fuller rationale onto it, deleted the duplicate.

3. tests/unit/test_ed25519.c — collateral from the same merge. Two copies of
   test_ed25519_identity_key_forgery_rejected, main() calling it twice and two
   tests not at all, and test_ed25519_low_order_R_with_a_valid_key_is_not_a_forgery
   referencing k_low_order[] and messages[] that the merge had dropped.

   While restoring the corpus, corrected it (review finding on #86): the array
   claimed to hold "the eight low-order point encodings" and held five. Every
   order here was computed rather than copied — decode y, recover x, add the
   point to itself until it reaches the identity — giving 1, 2, 4, 4, 8, 8, 8,
   8. Missing before: y=0 with the sign bit set, and both sign-flipped order-8
   encodings. D9FF..FF was in the array and is not a low-order point at all —
   no x satisfies the curve equation for that y — so it moves to a separate
   k_non_canonical[], with EDFF..FF7F (y=p) and EEFF..FF7F (y=p+1).

   tests_run was assigned a literal (11) in main() and never incremented,
   which is how the duplicate call and the two unregistered tests went
   unnoticed. The TEST macro now increments it, so the total cannot drift.

Verified:
  cmake -DEBLDR_BUILD_TESTS=ON on master   FAILS to build, 3 errors
  same with this commit                    builds clean
  ctest                                    21/21 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   21/21 PASS
  pytest tests/                            24 passed, 1 skipped
  test_ed25519                             14/14 PASS (was 11 claimed, 12 run)
  discrimination, with `public_key_is_valid_subgroup` disabled:
    test_ed25519_low_order_keys_rejected   FAILS, as it must
    test_ed25519_non_canonical_...         still PASSES — those are refused by
      unpackneg() on canonicality, a different mechanism, which is the reason
      they are held in a separate array rather than counted among the eight.

* test: derive the suite totals and the Valgrind list instead of restating them

Two findings arrived one after another in review, on different PRs, with the
same shape underneath: a number or a list that describes what the tests do,
written out separately from the thing it describes, with nothing checking the
two agree. Fixing them one instance at a time was going to keep producing the
same finding, so this fixes the class and adds the guard.

**1. Suites stated a total instead of counting one.** The `TEST()` macro
incremented `tests_passed`; `main()` assigned `tests_run = <literal>`. A test
defined but never wired into `main()` was skipped with a zero exit, and the
suite still reported "N/N passed" for an N that was a claim.

  18 of 21 suites carried it. It was not theoretical:

  - `test_ed25519.c` had a hardcoded 11 that masked one test called twice and
    two never called at all (repaired in #94, which is where this started).
  - `test_tlv_auth.c` assigns `tests_run` twice in one function -- 8, then 7.
    The stale 8 survives only because the later assignment wins. Its suite
    reports 7/7 today by luck.
  - `test_secure_boot.c` counted nothing and ended `return 0`, so a suite that
    ran none of its cases still reported success. The ASSERT macro exits on
    failure, so that return could only ever have signalled the one case it
    ignored.

  `TEST()` now increments `tests_run` where it invokes the test, every literal
  assignment and every `%d/<literal>` in a summary is gone, and
  `test_secure_boot.c` compares and returns accordingly.

**2. The Valgrind list named its suites again by hand**, and had drifted to 17
of 21 -- `test_ecc`, `test_rollback`, `test_secure_boot` and `test_storage`
got no memory-safety run, and nothing failed when a name was forgotten.
Each `add_test()` now appends to `EBLDR_UNIT_TESTS` and the `foreach` iterates
that, so a suite added without touching the block still gets a Valgrind
target. Confirmed with a stub `valgrind` on PATH: 21 `valgrind_*` tests are
generated, up from 17.

**3. tests/unit/test_suite_bookkeeping.py** keeps both from returning. Four
checks, no C toolchain needed: no suite hardcodes its own total; every
`TEST()` macro counts the test it runs; every defined test is actually called;
and the Valgrind list is derived rather than repeated. Three suites with no
`TEST()` macro are listed in `NO_TEST_MACRO` with a reason each.

Verified:
  ctest                                    21/21 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   21/21 PASS
  pytest tests/                            42 passed
  valgrind targets, with a stub on PATH    21 (was 17)
  every suite's reported total now equals what it ran -- e.g. test_bootctl
    12/12, test_tlv_auth 7/7, test_secure_boot 4/4

  Each of the four guards was probed against the defect it is written for:
    reintroduce `tests_run = 12`            -> test_bootctl.c: tests_run = 12
    remove `tests_run++` from the macro     -> FAIL
    stop calling a defined TEST()           -> FAIL
    drop a suite from EBLDR_UNIT_TESTS      -> FAIL
  and all four pass again on restore.

Refs #94, #80, #82

---------

Co-authored-by: Srikanth Patchava <srikanth.patchava@outlook.com>
srpatcha pushed a commit that referenced this pull request Sep 8, 2026
…ing GCM (#80)

* fix: repair master — the ABI asserts and the Ed25519 verifier both merged broken

master (22d8f8b) does not compile. Two independent double-merges, both the
same shape: two PRs fixing adjacent things landed on stale bases, each was
green on its own branch, and the result was never rebuilt.

1. include/eos_image.h — #93 replaced reserved[30] with tlv_len (2) +
   tlv_hash[28], preserving every offset. #87 merged afterwards carrying
   asserts written against the older struct:

     error: no member named 'reserved' in 'eos_image_header_t'   (x2)

   #93 already asserts tlv_len at 62 and tlv_hash at 64, so the offset assert
   was a duplicate; the width assert had no replacement and is restored as two
   asserts covering both halves of the same 30-byte span. No offset moves and
   the wire format is unchanged.

2. core/ed25519_verify.c — #86 and #57 both landed a subgroup guard, so the
   file carried two byte-identical point_is_identity() definitions:

     error: redefinition of 'point_is_identity'

   Only #57's public_key_is_valid_subgroup() is wired to the call site, so
   #86's key_has_prime_order() was dead. Kept the live function, folded #86's
   fuller rationale onto it, deleted the duplicate.

3. tests/unit/test_ed25519.c — collateral from the same merge. Two copies of
   test_ed25519_identity_key_forgery_rejected, main() calling it twice and two
   tests not at all, and test_ed25519_low_order_R_with_a_valid_key_is_not_a_forgery
   referencing k_low_order[] and messages[] that the merge had dropped.

   While restoring the corpus, corrected it (review finding on #86): the array
   claimed to hold "the eight low-order point encodings" and held five. Every
   order here was computed rather than copied — decode y, recover x, add the
   point to itself until it reaches the identity — giving 1, 2, 4, 4, 8, 8, 8,
   8. Missing before: y=0 with the sign bit set, and both sign-flipped order-8
   encodings. D9FF..FF was in the array and is not a low-order point at all —
   no x satisfies the curve equation for that y — so it moves to a separate
   k_non_canonical[], with EDFF..FF7F (y=p) and EEFF..FF7F (y=p+1).

   tests_run was assigned a literal (11) in main() and never incremented,
   which is how the duplicate call and the two unregistered tests went
   unnoticed. The TEST macro now increments it, so the total cannot drift.

Verified:
  cmake -DEBLDR_BUILD_TESTS=ON on master   FAILS to build, 3 errors
  same with this commit                    builds clean
  ctest                                    21/21 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   21/21 PASS
  pytest tests/                            24 passed, 1 skipped
  test_ed25519                             14/14 PASS (was 11 claimed, 12 run)
  discrimination, with `public_key_is_valid_subgroup` disabled:
    test_ed25519_low_order_keys_rejected   FAILS, as it must
    test_ed25519_non_canonical_...         still PASSES — those are refused by
      unpackneg() on canonicality, a different mechanism, which is the reason
      they are held in a separate array rather than counted among the eight.

* fix(fw_decrypt): drop a HW-crypto shortcut that cannot express streaming GCM

core/fw_decrypt.c is a hand-written AES-256-GCM sitting in the secure boot
path with no tests. It has an opt-in fast path:

    if (ops && ops->hw_aes_decrypt) {
        int rc = ops->hw_aes_decrypt(ctx->key, EOS_AES_KEY_SIZE,
                                     ctx->iv, data, data, len);
        if (rc == EOS_OK) { ctx->bytes_processed += len; return EOS_OK; }
    }

The hook is (key, key_len, iv, in, out, len). That signature cannot carry
streaming GCM, and taking the path broke decryption two ways:

1. No counter position. ctx->iv is passed unchanged on every call, so a second
   chunk restarts the CTR keystream at block 0 and is decrypted against the
   same keystream as the first. Reusing a CTR keystream across two plaintexts
   is the one thing the mode must never do.

2. No GHASH. The hook returns plaintext only, so ctx->ghash_acc is never fed.
   eos_fw_decrypt_final() computes the tag over an empty accumulator and
   rejects the image -- a board with an AES engine could not install a
   correctly encrypted firmware update at all.

(2) is why this was never noticed: it fails closed, and no board in-tree
implements the hook yet. (1) is why it cannot be patched by also feeding
GHASH: the plaintext would still be wrong past the first chunk. Re-enabling
needs a hook that takes a block offset and either exposes GHASH state or does
the whole GCM operation including the tag. Removed, with that written down
where the next person will look.

Also adds tests/unit/test_fw_decrypt.c -- the first tests this file has had.
Vectors come from an independent implementation (Python cryptography, i.e.
OpenSSL) rather than from this code, so they pin behaviour rather than
recording it:

  - whole blocks, and a 20-byte payload with a partial trailing block
  - the same ciphertext split [32] / [16,16] / [10,22] / [1,31] / [5,15]:
    GCM is a stream, so the result must not depend on how the caller sliced it
  - a board advertising a working AES engine must reach the same answer as one
    without -- this is the case that fails on master
  - every single-bit flip in the tag (128 of them), and in each ciphertext
    byte, must be rejected
  - unprovisioned/unreadable OTP keys and uninitialised contexts are refused

Verified: 8/8 pass with this change; against the unmodified fw_decrypt.c the
suite fails on
test_board_with_aes_engine_still_accepts_a_genuine_image, the assertion it
exists to make. The software GCM itself is correct -- I checked it against the
reference vectors before changing anything, including every chunk split above.

Note: the full test build on master is currently broken by test_image_verify.c
(fixed in #77), so this target was built directly.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(fw_decrypt): answer the review — stale doc, orphaned hook, anchor clash

Three findings from the review on #80, all in files this branch already owns.

Finding 2 (Medium) -- core/fw_decrypt.c's file header still read "Falls back
to HAL hw_aes_decrypt if available." The diff started at line 192, so that
line survived and directly contradicted the twenty-line rationale this PR
installs below it. A self-contradictory file is worse than the original.

Finding 1 (Medium) -- after the removal, hw_aes_decrypt has zero call sites
while eos_hal.h still advertises it under "software fallback used if NULL",
which is now false in the other direction: a board author who implements the
hook gets nothing, silently, with no diagnostic. That is the same class of
failure this PR is fixing. Kept the member rather than deleting it -- removing
it from a public struct is an ABI change for out-of-tree boards, and the hook
is worth having once it can express the operation -- and documented it as
reserved and currently unconsumed, with the reason and with what a
streaming-capable replacement would need.

Finding 3 (Low) -- this PR and #82 both inserted their add_executable/add_test
triple immediately after add_test(NAME test_keystore ...), so whichever landed
second would have conflicted for no reason but placement. Re-anchored this
one to the end of the registrations, with a comment saying why.

Also rebased: this branch was 7 commits behind and its diff against current
master would have reverted the test_recovery link-line fix. It is now stacked
on #94, which repairs master -- without that, every PR that builds the test
suite is red on include/eos_image.h and core/ed25519_verify.c.

Verified:
  cmake --build (EBLDR_BUILD_TESTS=ON)   clean
  ctest                                  22/22 PASS
  test_fw_decrypt                        8/8 PASS
  git grep hw_aes_decrypt                header + this file's comment only

Refs #80

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
srpatcha pushed a commit that referenced this pull request Sep 8, 2026
…ugs (#101)

* fix: repair master — the ABI asserts and the Ed25519 verifier both merged broken

master (22d8f8b) does not compile. Two independent double-merges, both the
same shape: two PRs fixing adjacent things landed on stale bases, each was
green on its own branch, and the result was never rebuilt.

1. include/eos_image.h — #93 replaced reserved[30] with tlv_len (2) +
   tlv_hash[28], preserving every offset. #87 merged afterwards carrying
   asserts written against the older struct:

     error: no member named 'reserved' in 'eos_image_header_t'   (x2)

   #93 already asserts tlv_len at 62 and tlv_hash at 64, so the offset assert
   was a duplicate; the width assert had no replacement and is restored as two
   asserts covering both halves of the same 30-byte span. No offset moves and
   the wire format is unchanged.

2. core/ed25519_verify.c — #86 and #57 both landed a subgroup guard, so the
   file carried two byte-identical point_is_identity() definitions:

     error: redefinition of 'point_is_identity'

   Only #57's public_key_is_valid_subgroup() is wired to the call site, so
   #86's key_has_prime_order() was dead. Kept the live function, folded #86's
   fuller rationale onto it, deleted the duplicate.

3. tests/unit/test_ed25519.c — collateral from the same merge. Two copies of
   test_ed25519_identity_key_forgery_rejected, main() calling it twice and two
   tests not at all, and test_ed25519_low_order_R_with_a_valid_key_is_not_a_forgery
   referencing k_low_order[] and messages[] that the merge had dropped.

   While restoring the corpus, corrected it (review finding on #86): the array
   claimed to hold "the eight low-order point encodings" and held five. Every
   order here was computed rather than copied — decode y, recover x, add the
   point to itself until it reaches the identity — giving 1, 2, 4, 4, 8, 8, 8,
   8. Missing before: y=0 with the sign bit set, and both sign-flipped order-8
   encodings. D9FF..FF was in the array and is not a low-order point at all —
   no x satisfies the curve equation for that y — so it moves to a separate
   k_non_canonical[], with EDFF..FF7F (y=p) and EEFF..FF7F (y=p+1).

   tests_run was assigned a literal (11) in main() and never incremented,
   which is how the duplicate call and the two unregistered tests went
   unnoticed. The TEST macro now increments it, so the total cannot drift.

Verified:
  cmake -DEBLDR_BUILD_TESTS=ON on master   FAILS to build, 3 errors
  same with this commit                    builds clean
  ctest                                    21/21 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   21/21 PASS
  pytest tests/                            24 passed, 1 skipped
  test_ed25519                             14/14 PASS (was 11 claimed, 12 run)
  discrimination, with `public_key_is_valid_subgroup` disabled:
    test_ed25519_low_order_keys_rejected   FAILS, as it must
    test_ed25519_non_canonical_...         still PASSES — those are refused by
      unpackneg() on canonicality, a different mechanism, which is the reason
      they are held in a separate array rather than counted among the eight.

* fix(fuzz): point every harness at the API it claims to fuzz

Four of the five fuzz harnesses did not test what they name, and the
build could not say so because not one of them includes a project
header. Each declares its target itself:

  fuzz_recovery_protocol.c  extern int eos_recovery_parse_packet(...)
  fuzz_fw_update.c          extern int eos_fw_update_init(void)
                            extern int eos_fw_update_process_chunk(...)
                            extern int eos_fw_update_finalize(void)
  fuzz_bootctl.c            extern int eos_bootctl_parse(...)
  fuzz_image_verify.c       extern int eos_image_parse_header(const void *, size_t)

eos_recovery_parse_packet, eos_fw_update_init,
eos_fw_update_process_chunk and eos_bootctl_parse have never existed —
those names appear nowhere outside the harness that declares them, so
three of the five targets have never linked.

The other two are worse, because they do link:

  - eos_fw_update_finalize exists but takes (ctx, mode), not (void).
  - eos_image_parse_header takes (uint32_t addr, eos_image_header_t *),
    not (const void *, size_t). fuzz_image_verify has been passing a
    pointer where an address is expected and a length where an output
    struct is expected, on every input, for as long as it has run.

A local extern is why none of this was caught: it tells the compiler the
symbol exists with whatever shape the harness asserts, and the mismatch
survives to link time or past it.

All five now include the real header and drive the real entry points:

  fuzz_image_verify       parse_header -> verify_integrity, boot-path order
  fuzz_bootctl            bootctl_load, then trap if load() accepted a
                          block validate() rejects
  fuzz_fw_update          begin -> write in fuzz-chosen chunk widths ->
                          finalize or abort
  fuzz_recovery_protocol  write_in_range, trapping on any accepted write
                          that leaves the slot or wraps, checked in wider
                          types that cannot
  fuzz_crypto             already correct; switched to the header so it
                          stays that way

Adds tests/fuzz/fuzz_sim_flash.h: the three harnesses that reach flash
need board ops installed, and without them they fuzz a null op table.

That the compiler now checks this is not theoretical — writing this, it
rejected EOS_UPGRADE_MODE_TEST for EOS_UPGRADE_TEST immediately, which
is exactly the error class the externs were hiding.

Verified. libFuzzer is unavailable here (libclang_rt.fuzzer_osx.a not
found), so each harness was linked against eboot_core and driven by a
standalone seed generator under ASan+UBSan:

  all five compile -Wall -Wextra    5/5, 0 failures
  20,000 inputs each               100,000 total, no reports
  ctest                            21/21 passed

Third instance of this class across these repos, after eos#50
(fuzz_devicetree naming eos_dtb_parse) and eos#110 (fuzz_ota_header
naming eos_ota_parse_header). The common factor every time is a fuzz
target declaring its own subject.

Stacked on #94, without which include/eos_image.h does not compile.

* fix(fuzz): the recovery oracle was off by one, and CI proved it

The restored Fuzz Harness Build job on #101 ran these harnesses under
real libFuzzer for the first time and fuzz_recovery_protocol trapped
within seconds. That was my bug, not the code's.

The oracle computed the one-past-the-end address:

    end = base + offset + len;  if (end > 0xFFFFFFFF) trap;

The last byte a write of len bytes touches is base + offset + len - 1.
eos_recovery_write_in_range() checks exactly that:

    if ((uint32_t)len - 1u > UINT32_MAX - (base + offset)) reject;

So an accepted write whose final byte lands exactly on 0xFFFFFFFF --
base=0xFFFFFF00, offset=0, len=256 -- is legal, the function accepts it,
and the old oracle trapped on it. A harness that traps on valid input
reports the opposite of the truth.

Verified both directions:
  the boundary case, fed directly      -> no trap
  a fail-open stub accepting all input -> trap fires (exit 133)
  500,000 random inputs, ASan+UBSan    -> no reports

libFuzzer doing precisely what it is for -- driving inputs into the one
corner a hand-written oracle got wrong -- is the strongest argument yet
for #101's job. The guard could never have caught this; only execution
under a coverage-driven fuzzer did.

* ci(fuzz): compile the harnesses, and refuse the extern that hid the bugs

#99 repairs the five harnesses in tests/fuzz/. Neither it nor anything
else stops the same thing happening again, because two of the conditions
that produced it are still in place.

**Nothing compiles them.** tests/fuzz/ is behind EBLDR_BUILD_FUZZ, which
defaults OFF, and no job set it. That is the whole reason three harnesses
could name functions that exist nowhere -- eos_bootctl_parse,
eos_recovery_parse_packet, eos_fw_update_init and friends -- and sit there
for as long as they did. A harness that is not built cannot fail to build.
The fuzz-build job restores that: clang, EBLDR_BUILD_FUZZ=ON (and
EBLDR_BUILD_TESTS=ON, since tests/fuzz is added from tests/CMakeLists.txt,
so the option alone would build nothing and the job would pass having
compiled no harness at all), then a five-second smoke run of each target.
It does not fuzz; a real campaign belongs in a scheduled workflow.

**The `extern` is still legal.** Every one of the four defects came from a
hand-written prototype standing in for an #include -- a promise the
compiler is obliged to believe and has no way to check. It is what made
the fourth defect invisible even to a compiler: fuzz_image_verify declared
eos_image_parse_header as (const void *, size_t) when it is
(uint32_t, eos_image_header_t *), so that harness linked, ran, and fuzzed
nothing. tests/unit/test_fuzz_harnesses.py refuses the pattern, and also
checks that every harness is built by a CMake target, links eboot_core,
and defines LLVMFuzzerTestOneInput.

The two halves cover different failures: the guard is static and stops the
pattern being written, the job is a compiler and catches a signature that
drifts under a harness that includes the right header. Neither subsumes
the other.

Mutation-checked: restoring one extern prototype fails
test_no_harness_declares_its_own_prototypes; deleting one add_executable
fails test_every_harness_is_built.

Verified: pytest tests/unit 26 passed 1 skipped, ctest 21/21. The fuzz job
itself could not be run here -- Apple clang ships no libclang_rt.fuzzer, so
-fsanitize=fuzzer will not link on this host. Instead each of #99's five
harnesses was compiled and linked against eboot_core with a stand-in driver
under -fsanitize=address,undefined and run over ~20k pseudo-random inputs
plus every length from 0 to 200; all five clean. That covers the symbol
resolution and the harness logic, which is what the job's build step
checks; it does not prove the libFuzzer link itself, which only CI can.
srpatcha added a commit that referenced this pull request Sep 8, 2026
…85)

* fix: repair master — the ABI asserts and the Ed25519 verifier both merged broken

master (22d8f8b) does not compile. Two independent double-merges, both the
same shape: two PRs fixing adjacent things landed on stale bases, each was
green on its own branch, and the result was never rebuilt.

1. include/eos_image.h — #93 replaced reserved[30] with tlv_len (2) +
   tlv_hash[28], preserving every offset. #87 merged afterwards carrying
   asserts written against the older struct:

     error: no member named 'reserved' in 'eos_image_header_t'   (x2)

   #93 already asserts tlv_len at 62 and tlv_hash at 64, so the offset assert
   was a duplicate; the width assert had no replacement and is restored as two
   asserts covering both halves of the same 30-byte span. No offset moves and
   the wire format is unchanged.

2. core/ed25519_verify.c — #86 and #57 both landed a subgroup guard, so the
   file carried two byte-identical point_is_identity() definitions:

     error: redefinition of 'point_is_identity'

   Only #57's public_key_is_valid_subgroup() is wired to the call site, so
   #86's key_has_prime_order() was dead. Kept the live function, folded #86's
   fuller rationale onto it, deleted the duplicate.

3. tests/unit/test_ed25519.c — collateral from the same merge. Two copies of
   test_ed25519_identity_key_forgery_rejected, main() calling it twice and two
   tests not at all, and test_ed25519_low_order_R_with_a_valid_key_is_not_a_forgery
   referencing k_low_order[] and messages[] that the merge had dropped.

   While restoring the corpus, corrected it (review finding on #86): the array
   claimed to hold "the eight low-order point encodings" and held five. Every
   order here was computed rather than copied — decode y, recover x, add the
   point to itself until it reaches the identity — giving 1, 2, 4, 4, 8, 8, 8,
   8. Missing before: y=0 with the sign bit set, and both sign-flipped order-8
   encodings. D9FF..FF was in the array and is not a low-order point at all —
   no x satisfies the curve equation for that y — so it moves to a separate
   k_non_canonical[], with EDFF..FF7F (y=p) and EEFF..FF7F (y=p+1).

   tests_run was assigned a literal (11) in main() and never incremented,
   which is how the duplicate call and the two unregistered tests went
   unnoticed. The TEST macro now increments it, so the total cannot drift.

Verified:
  cmake -DEBLDR_BUILD_TESTS=ON on master   FAILS to build, 3 errors
  same with this commit                    builds clean
  ctest                                    21/21 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   21/21 PASS
  pytest tests/                            24 passed, 1 skipped
  test_ed25519                             14/14 PASS (was 11 claimed, 12 run)
  discrimination, with `public_key_is_valid_subgroup` disabled:
    test_ed25519_low_order_keys_rejected   FAILS, as it must
    test_ed25519_non_canonical_...         still PASSES — those are refused by
      unpackneg() on canonicality, a different mechanism, which is the reason
      they are held in a separate array rather than counted among the eight.

* fix(fdt): bound a device tree parser that was never compiled

core/fdt_loader.c is in no source list, so it has never been built. The
header offers it to callers, rtos_boot.c is named as the consumer, and
nothing catches what is in it -- not the compiler, not ctest, not the
sanitizer job.

What is in it is a parser for a blob that comes out of flash, whose every
header field it uses as an offset or a length without checking any of
them. eos_fdt_validate() looks at magic and version only, so it accepts
a blob whose off_dt_struct points anywhere:

    hdr.totalsize     = 40      (the header alone)
    hdr.off_dt_struct = 0x100000
    eos_fdt_validate(blob) -> 0
    eos_fdt_get_prop(...)  -> AddressSanitizer: BUS, READ at
                              fdt_loader.c:25 in fdt_read_u32

Five more, all reachable the same way:

* the tag read at the top of the loop takes 4 bytes where the loop
  condition guarantees 1;
* strlen() on a node name reads until it finds a zero, which for a name
  running to the end of the block is past it;
* nameoff indexes the strings block unchecked, so strcmp() reads from an
  arbitrary address;
* a property len is clamped to the caller's buffer before the memcpy,
  which bounds the write but not the read -- an oversized len copies
  whatever follows the blob out to the caller;
* FDT_END_NODE decrements depth with no floor.

Bound them. validate() is the gate every path goes through, so the block
offsets are checked against totalsize there, and get_prop() calls it
before trusting the header. Inside the loop each read is checked for the
width it takes, the name and property-name scans are bounded by memchr
within their blocks, and the padded advances are re-checked for overrun.

Adds the file to eboot_core and tests/unit/test_fdt_loader.c to ctest:
ten cases, one well-formed tree that must still parse and nine malformed
ones. Against the unfixed parser the suite fails on the third; with the
bounds in place the whole suite is 20/20, and 20/20 under EBLDR_SANITIZE.

Not fixed here, because it is a behaviour change rather than a safety
one: node paths below the root do not resolve. _get_prop derives the
depth to match from a slash count, so "/chosen" looks for depth 1, which
is the root -- "chosen" is at depth 2. Only "/" resolves today.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(fdt): bound the parser against the caller's length, not the blob's claim

Follow-up to the review on #84. Three findings from it, all in files this
branch already owns.

Finding 1 (High) -- every bound in eos_fdt_validate() was expressed relative
to hdr->totalsize, which is read out of the same untrusted blob. Checking the
block offsets against it proves the header is internally consistent and says
nothing about how many bytes are really mapped: a 40-byte buffer declaring
totalsize = 0x100000 with agreeing offsets passed every check, and
eos_fdt_get_prop() then walked a megabyte past the allocation. The original
reproducer (an inflated *offset* against an honest totalsize) was rejected;
its mirror image was not.

Adds the length-carrying entry points eos_fdt_validate_sized() and
eos_fdt_get_prop_sized(), which take the bytes the caller actually owns and
check totalsize against that before anything else. The existing two-argument
forms stay as wrappers that trust the blob's own totalsize, documented in the
header as a warrant the caller has to make good; eos_fdt_load() now passes
max_size, which it had all along.

Finding 2 (Medium) -- a property larger than the caller's buffer was copied
short and reported as success, so a clipped value was indistinguishable from
a complete one. In a boot path this reads bootargs. Now returns -7 and sets
*buf_len to the full length so the caller can size a retry.

Finding 3 (Medium) -- adds tests/fuzz/fuzz_fdt.c alongside the five existing
harnesses. .ai/security.md names device tree among the parsers that get fuzz
coverage rather than unit tests alone. It drives the sized entry points and
passes the real size, which is what makes the harness meaningful -- the
unsized forms would let a fuzzer authorise its own out-of-bounds read.

Finding 6 (Low) -- drops the unreachable `total < sizeof(fdt_header_t)` check
in eos_fdt_load(); validate() already rejects that blob, and the comment
above it described a bound it was not applying.

Header now documents the full -1..-8 return code table.

Verified:
  cmake -DEBLDR_BUILD_TESTS=ON, ctest              21/21 PASS
  same under -DEBLDR_SANITIZE=ON (ASan+UBSan)      21/21 PASS
  test_fdt_loader                                  14 tests PASS (was 10)
  new tests against the pre-fix parser             both FAIL as they should
    - inflated totalsize accepted at the sized entry point
    - truncating call returned 0 instead of -7
  grep for eos_fdt_get_prop / eos_fdt_validate     no callers outside the
    parser and its tests, so the -7 change breaks nothing today

Refs #84

* fix(build): drop the duplicate core/fdt_loader.c registration

master gained core/fdt_loader.c in eboot_core while this branch was open, so
after the rebase it appeared twice and
tests/unit/test_cmake_core_sources.py::test_core_sources_are_registered_once
failed:

    AssertionError: ['core/fdt_loader.c'] is not false :
    duplicate eboot_core sources: ['core/fdt_loader.c']

Kept master's entry, dropped the one this branch added. That guard is the
same shape as the one this stack adds for toolchain specs -- a build-file
check that catches the class rather than the instance -- and it did its job.

Verified: ctest 22/22 PASS, pytest 24 passed 1 skipped.

Refs #84

* fix(fdt): one length-carrying API, and a CI job that builds the fuzz harnesses

Answers the second review on #84.

Finding 2 (Medium) -- eos_fdt_validate() and eos_fdt_get_prop() kept an
out-of-bounds read by design. Both dereferenced hdr->totalsize before any
length was known and handed that attacker-controlled value to the _sized form
as its bound, so calling either on a short buffer read past it before a single
check had run. The header called that a caller warrant; a warrant is not a
check, and it is the exact bug this PR exists to fix. Neither had an in-tree
caller.

Removed rather than documented. There is now one form of each entry point and
it always takes the length:

    int eos_fdt_validate(const void *fdt_blob, uint32_t avail);
    int eos_fdt_get_prop(const void *fdt, uint32_t fdt_len, ...);

An exported unsafe twin in a TCB header is a future boot-path caller
reintroducing the bug with no compiler complaint, which is worth more than the
convenience of a one-argument call. eos_fdt_load() already passed max_size.
The test that pinned the wrapper's behaviour is gone with the wrapper, and
get_prop_sized_exact() collapsed into get_prop_exact() since they became the
same function.

Finding 3 (Medium) -- tests/fuzz/ was built by nothing. EBLDR_BUILD_FUZZ
defaults OFF and no job set it, so the harness added here joined five others
that no CI job compiles. A harness that is never built cannot fail to build,
which is how fuzz_devicetree came to declare a function that did not exist and
sit there unnoticed (eos#50).

Adds a `fuzz-build` job: configure with clang, build every harness, and run
each for five seconds over its own generated inputs. That is not a campaign --
it is enough to catch a harness that no longer compiles or crashes at once,
which is the failure this repo has actually had. Note it needs
EBLDR_BUILD_TESTS=ON as well: tests/fuzz/ is added from tests/CMakeLists.txt,
so EBLDR_BUILD_FUZZ alone configures cleanly and builds no harness at all --
the job would have passed having compiled nothing. Found that locally before
writing the job, not after.

  NOT RUN, and this is the honest limit: this host has no libFuzzer runtime
  (libclang_rt.fuzzer_osx.a is absent from the Xcode toolchain), so the link
  step cannot be reproduced here for any harness, old or new. What I verified
  is that CMake configures with both flags and reports all six targets --
  "Fuzz targets: fuzz_image_verify, fuzz_recovery_protocol, fuzz_fw_update,
  fuzz_crypto, fuzz_bootctl, fuzz_fdt" -- and that fuzz_fdt.c passes
  `cc -fsyntax-only`. The link and the smoke run are CI's to show, and this
  job is what makes them visible.

  Coordination note: #90 adds a `CI Gate` whose needs list is
  [test, build-arm, static-analysis]. Whichever of #84 and #90 lands second
  must add fuzz-build to that list -- and #90's own
  test_gate_covers_every_job_that_runs_on_a_pull_request fails loudly if it is
  not, which is the guard working rather than a trap.

Finding 1 (High) is a PR-body correction, made there: the diff carries #94's
master repair because this branch is stacked on it, and the body described
only the FDT parser.

Verified:
  ctest                                    22/22 PASS
  pytest tests/                            38 passed
  test_fdt_loader                          13 tests PASS
  grep for a length-free entry point       none remains in the header

Refs #84

* ci: move the fuzz-harness build to its own PR

The fuzz-build job added in the previous commit does its job -- it is red, on
harnesses this PR did not write:

    undefined reference to `eos_fw_update_init'
    undefined reference to `eos_fw_update_process_chunk'
    undefined reference to `eos_recovery_parse_packet'

None of those exist anywhere in the tree. tests/fuzz/fuzz_fw_update.c and
fuzz_recovery_protocol.c declare an API that was never written, exactly as
eos#50's fuzz_devicetree declared eos_dtb_parse(). They have compiled forever
because nothing ever linked them.

That is a real finding and it deserves a fix, not a red tick on an unrelated
PR. The job and the repairs move to their own change; this PR keeps
tests/fuzz/fuzz_fdt.c, which is the harness it is responsible for.

Refs #84

* fix(fdt): read the header the way the struct block is read, and stop resynchronising on garbage

Answers the third review on #84.

Finding 3 (Low, and the one that matters on hardware) -- the header was read
through a cast fdt_header_t* and direct member loads, while every struct-block
read goes through the fdt_read_u32() memcpy helper precisely because the blob
may be unaligned. Fuzz input, a buffer inside a larger message, a copy at an
odd offset: nothing promises 4-byte alignment, and on a strict-alignment
cross target a direct member load is the same fault class this parser exists
to avoid. The unit suite could never catch it -- blob_t.bytes happens to be
aligned.

All header fields now go through fdt_hdr_u32() (memcpy at offsetof), one rule
for the whole blob, in validate(), load() and get_prop(). FUZZ_FLAGS gains
`undefined` so the fuzz job checks alignment too.

Finding 4 (Low) -- `default: break;` resynchronised on unrecognised tags: the
walk skipped 4 bytes and treated whatever followed as the next token, so a
struct block of arbitrary bytes parsed to a clean "not found". Bounded, but a
TCB parser that walks garbage to completion is accepting input it does not
understand. FDT_NOP -- the one legal unknown, padding the spec allows between
tokens -- is now named in the header and passes; anything else returns -6.

Findings 1, 2 and the -8 line: the fuzz-build job's single home is #101
(nothing added here; the harness is inert until that job lands and then
compiled by it -- said on the thread, not just here), and the header no longer
documents return code -8, which nothing at this head returns. #85 adds the -8
return and re-documents it together with the FDT_MAX_PATH_DEPTH move.

Verified:
  ctest                                    22/22 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   22/22 PASS
  pytest tests/                            38 passed
  test_fdt_loader                          16 tests PASS (was 13)
  discrimination, each fix in isolation:
    default: break restored     -> test_a_garbage_tag_is_refused_not_skipped
                                   FAILS (expects -6, gets "not found")
    direct member load restored -> under UBSan the new unaligned-blob test
                                   reports "load of misaligned address
                                   0x...671 for type 'const uint32_t'" at the
                                   exact line -- and cannot fire on the fixed
                                   code, which runs the same test clean
  NOP counter-check: interleaved FDT_NOP tokens still resolve, so the
  stricter default does not reject real trees.

Refs #84

* fix(fdt): resolve a node by its path, not by its depth and last name

Replaces slash-counting and last-component matching with a component walk
gated on ancestor matches, so /soc/uart and /decoy/uart are distinguishable.

Also carries the fixes from the review on this PR:

Finding 1 (High) -- the property arm tested in_target alone, and in_target is
cleared only by the target's own FDT_END_NODE, so it stayed true for the
entire subtree and a property found on a *child* was returned as the target's
own. On this PR's own decoy tree, eos_fdt_get_prop(blob, "/soc", "reg", ...)
returned 0 with "soc-uart" when /soc has no reg property at all and the
correct answer is -5. Real device trees emit properties before subnodes, so a
property that is present on the target is still found first -- the bug bites
when the target lacks it, turning "not found" into a silently wrong value
from a nested node. For an attacker-supplied blob the ordering is not
enforced at all. Fixed by also requiring depth == target_depth, which is
exact: depth is target_depth for the target's own properties and
target_depth + 1 or deeper inside any child.

Finding 2 (Low) -- test_the_parent_of_the_node_has_to_match_too asserted a
second positive resolution rather than a rejection, so the suite read as
though it had a negative case for wrong parents when the negative coverage
actually lives in test_a_node_below_the_root_resolves. Renamed to
test_each_uart_returns_its_own_value, and the load-bearing property (decoy is
emitted before soc, so a last-component matcher would return "decoy-uart")
is now stated on the test that depends on it.

Finding 3 (Low) -- a path deeper than FDT_MAX_PATH_DEPTH returned -1, the
same code as a NULL argument, so a caller could not tell a programming error
from malformed input. Now -8, documented in the header's code table.

Verified:
  ctest                                            21/21 PASS
  same under -DEBLDR_SANITIZE=ON (ASan+UBSan)      21/21 PASS
  test_fdt_loader                                  20 tests PASS (was 14)
  test_a_property_on_a_child_is_not_returned_as_the_parents, run against
    this same parser with only the depth guard reverted:
      [FAIL] get_prop_exact(&b, "/soc", "reg", out, &len) != 0
    so it discriminates rather than restating the fix.

Refs #85

* fix(fdt): match node names past the unit address, where real device trees put it

Replaces slash-counting and last-component matching with a component walk
gated on ancestor matches, and matches a component against the node name up
to its unit address -- `/soc/uart` resolves `uart@40011000`, an explicit
`@40011000` still selects exactly that node, and an address not in the tree
does not fall back to a loose match.

Carries the earlier review fixes (depth == target_depth on the property arm;
FDT_MAX_PATH_DEPTH moved to the public header; -8 for an over-deep path,
distinct from -1) and, from the overnight round:

  - the stray `/* Deepest node path ... */` comment left in the .c after the
    define moved to the header is gone (Low)
  - return code -8 is documented in the header's code table again, on this
    branch, because this is the branch where anything returns it -- #84
    dropped the line for exactly that reason

Rebased onto #84's alignment/NOP round; the test-file merge keeps both sides'
suites (garbage-tag, NOP-padding and unaligned-blob from #84; the node-path
and unit-address suites from here).

Verified:
  ctest                                    22/22 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   22/22 PASS
  pytest tests/                            38 passed
  test_fdt_loader                          24 tests PASS

Refs #85

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Srikanth Patchava <srikanth.patchava@outlook.com>
srpatcha pushed a commit that referenced this pull request Sep 8, 2026
* fix: repair master — the ABI asserts and the Ed25519 verifier both merged broken

master (22d8f8b) does not compile. Two independent double-merges, both the
same shape: two PRs fixing adjacent things landed on stale bases, each was
green on its own branch, and the result was never rebuilt.

1. include/eos_image.h — #93 replaced reserved[30] with tlv_len (2) +
   tlv_hash[28], preserving every offset. #87 merged afterwards carrying
   asserts written against the older struct:

     error: no member named 'reserved' in 'eos_image_header_t'   (x2)

   #93 already asserts tlv_len at 62 and tlv_hash at 64, so the offset assert
   was a duplicate; the width assert had no replacement and is restored as two
   asserts covering both halves of the same 30-byte span. No offset moves and
   the wire format is unchanged.

2. core/ed25519_verify.c — #86 and #57 both landed a subgroup guard, so the
   file carried two byte-identical point_is_identity() definitions:

     error: redefinition of 'point_is_identity'

   Only #57's public_key_is_valid_subgroup() is wired to the call site, so
   #86's key_has_prime_order() was dead. Kept the live function, folded #86's
   fuller rationale onto it, deleted the duplicate.

3. tests/unit/test_ed25519.c — collateral from the same merge. Two copies of
   test_ed25519_identity_key_forgery_rejected, main() calling it twice and two
   tests not at all, and test_ed25519_low_order_R_with_a_valid_key_is_not_a_forgery
   referencing k_low_order[] and messages[] that the merge had dropped.

   While restoring the corpus, corrected it (review finding on #86): the array
   claimed to hold "the eight low-order point encodings" and held five. Every
   order here was computed rather than copied — decode y, recover x, add the
   point to itself until it reaches the identity — giving 1, 2, 4, 4, 8, 8, 8,
   8. Missing before: y=0 with the sign bit set, and both sign-flipped order-8
   encodings. D9FF..FF was in the array and is not a low-order point at all —
   no x satisfies the curve equation for that y — so it moves to a separate
   k_non_canonical[], with EDFF..FF7F (y=p) and EEFF..FF7F (y=p+1).

   tests_run was assigned a literal (11) in main() and never incremented,
   which is how the duplicate call and the two unregistered tests went
   unnoticed. The TEST macro now increments it, so the total cannot drift.

Verified:
  cmake -DEBLDR_BUILD_TESTS=ON on master   FAILS to build, 3 errors
  same with this commit                    builds clean
  ctest                                    21/21 PASS
  ctest -DEBLDR_SANITIZE=ON (ASan+UBSan)   21/21 PASS
  pytest tests/                            24 passed, 1 skipped
  test_ed25519                             14/14 PASS (was 11 claimed, 12 run)
  discrimination, with `public_key_is_valid_subgroup` disabled:
    test_ed25519_low_order_keys_rejected   FAILS, as it must
    test_ed25519_non_canonical_...         still PASSES — those are refused by
      unpackneg() on canonicality, a different mechanism, which is the reason
      they are held in a separate array rather than counted among the eight.

* fix(eos_sign): emit the layout master defines, not a new meaning for hdr_size

Answers the review on #88. Both High findings had the same root, and master
has since settled the question the reviewer said needed a decision.

The original defect is real and unchanged: the tool emitted
[header][TLV][payload] while stamping hdr_size as a fixed 156, so
core/image_verify.c's `payload_addr = addr + hdr->hdr_size` landed on the TLV
block and every image it produced failed integrity verification on-device.

This branch fixed it by moving hdr_size to mean "offset to the payload". That
was the wrong half to move.

Finding 1 (High) -- eFirmware/src/efw_image.c:122 checks
`hdr_size != EFW_IMAGE_HDR_SIZE` for exact equality against 156, so every TLV
image would have been rejected by the other half of the format, which
eFirmware's header documents as interchangeable.

Finding 2 (High) -- core/rollback.c computes the TLV address as
image_addr + hdr_size + image_size, i.e. it assumes the area follows the
payload. Under either the old layout or this branch's, the anti-rollback
EOS_TLV_MIN_SEC_VER could never be found, so the counter this repository gates
downgrades on was unreachable for every image the tool produced.

Master answers both, and it is the reviewer's option (b): #93 landed tlv_len
and tlv_hash in the header -- inside EOS_IMG_SIGNED_LEN -- and documents that
"the TLV area sits after the payload". So this PR now emits
[header][payload][TLV] with hdr_size always 156. eFirmware's equality check
keeps working untouched, rollback.c's arithmetic is correct as written, and no
field changes meaning.

That reordering also resolves an ordering problem the old shape had: the TLV
carried the signature, so its digest could not be computed before the
signature existed. The signature now lives in the header's signature[] field
and the TLV carries metadata only, which is what makes tlv_hash signable.

Finding 4 (Medium) -- the two `assert`s in cmd_sign are removed by `python -O`.
This is release-signing tooling, so the signature-length check is now a
`raise SystemExit`. The TLV-length assert is gone with the code that needed it.

Finding 5 (Medium) -- `pytest.importorskip("cryptography")` still skipped
silently if the install ever failed, leaving "collected 19, ran 0" as a green
run. Now gated: EOS_REQUIRE_SIGNING_TESTS is set in ci.yml, and under it the
module is imported directly so a missing dependency is a collection error.
Locally, without the variable, the skip still applies.

Finding 6 (Low) -- cmd_verify bounds-checks the image length before unpacking,
so a short file gets a FAIL: line rather than a struct.error traceback, and
the 156 is hoisted to EOS_IMG_STRUCT_SIZE rather than re-derived.

Finding 3 (Medium) needs no change here: master's include/eos_image.h already
documents the layout this now emits.

Rebased onto #94 (the master repair) and reduced to the five files that are
still this PR's own -- the branch was stale enough that its diff against
master would have reverted core/rollback.c, include/eos_image.h,
tests/unit/test_tlv_auth.c and the rest of #93's TLV work.

Verified:
  end to end, with the real tool:
      eos_sign.py keygen / sign / verify  -> VERIFIED
      total 744 = 156 header + 512 payload + 76 TLV
      hdr_size 156, tlv_len 76, TLV magic 0x6907 at 156+512
      sha256(tlv)[:28] == header bytes 64..92          True
  ctest                                    22/22 PASS
  test_eos_sign_boot_path (real parser over real tool output):
      current layout [hdr][payload][tlv]: verify_integrity -> 0   PASS
      old layout     [hdr][tlv][payload]: verify_integrity -> -3  PASS
      TLV magic at addr + hdr_size + image_size: 0x6907           PASS
    that third line is finding 2's regression test -- it fails on the old
    layout, where the address lands past the end of the image.
  pytest tests/ (EOS_REQUIRE_SIGNING_TESTS=1)          44 passed
  the CI gate itself: with the variable set and the module absent, the import
    raises ImportError -> collection error -> job fails, rather than skipping.

Refs #88, #93
Kartikey1306 added a commit to Kartikey1306/eBoot that referenced this pull request Sep 14, 2026
Twenty PRs were merged into master in ninety minutes on 09-07, each on the
base it was written against. Master has not configured, compiled, linked or
passed its tests since. Every nightly and every eos simulation run (which
builds eBoot master) has been red for the same reason.

Configure:
- tests/CMakeLists.txt registered eboot_test_fdt_loader twice. embeddedos-org#84 added it,
  and embeddedos-org#85 -- stacked on embeddedos-org#84 -- re-added it at a different anchor when it was
  replayed onto a master that already had embeddedos-org#84. Same hunk as embeddedos-org#111.

Compile (eboot_core):
- embeddedos-org#55 restored a core/sha512.c from 02b7dac that keeps its byte count in
  ctx->count; the eos_sha512_ctx_t master ships has bitlen[2]/buffer_len
  (embeddedos-org#69/embeddedos-org#93). Back to the pre-embeddedos-org#55 file, blob-identical (d9aa57c).
- embeddedos-org#55's source-list "correction" dropped core/boot_log.c, core/secure_boot.c
  and core/fdt_loader.c, which embeddedos-org#72/embeddedos-org#84 had added after embeddedos-org#55 was written.
  CMakeLists.txt is blob-identical to pre-embeddedos-org#55 again (f8fe6eb).
- embeddedos-org#55 replaced the eos_boot_log_get_head() declaration with a second copy of
  eos_boot_log_read(); embeddedos-org#91 had already fixed the prototype it meant to fix.
  Header restored (964ebb8).
- embeddedos-org#94 and embeddedos-org#105 each repaired the Ed25519 verifier and each added an identical
  static scalarbase(); both merged. One copy removed.
- The same pair each added k_low_order[]/messages[] to test_ed25519.c. The
  embeddedos-org#105 copy is removed; embeddedos-org#94's stays because it also carries k_non_canonical[].

Tests that stopped passing because two merged PRs disagree on behaviour:
- embeddedos-org#104 verifies the image signature at install unconditionally, before the
  anti-rollback check embeddedos-org#103 added, so embeddedos-org#103's unsigned images are refused as
  EOS_ERR_SIGNATURE before they can be refused as EOS_ERR_ANTI_ROLLBACK, and
  test_fw_transport's XMODEM install can no longer finalize. Both suites now
  stream genuinely signed images. eBoot has no Ed25519 signer in C, so
  tools/gen_fw_update_test_sigs.py signs the exact header prefixes those
  suites build under the RFC 8032 section 7.1 TEST 1 key and emits
  tests/vectors/fw_update_test_sigs.h; the suites serve that key from a
  simulated OTP slot 0. Negative control: one flipped signature byte fails
  test_write_streams_tlv_then_finalize_rejects_below_floor with
  EOS_ERR_SIGNATURE.
- embeddedos-org#103's step 5b reads the TLV counter through the HAL slot containing the
  image; test_secure_boot_policy (embeddedos-org#82) declared no slots, so eos_secure_boot()
  returned EOS_SBOOT_ERR_BAD_HEADER two steps before the one under test. The
  fixture now places its image in slot A.

Guards from embeddedos-org#95 that later merges walked back, never run until now because the
C configure step failed first:
- embeddedos-org#103 replayed the hand-written Valgrind foreach over the derived one.
  Restored foreach(TEST_NAME ${EBLDR_UNIT_TESTS}); eleven registered suites
  had no list(APPEND ...) and so no Valgrind run.
- Seven suites assign tests_run = <literal> and their TEST() does not count;
  four suites have no TEST() macro at all. Counted, and classified.
- embeddedos-org#101 added fuzz-build after embeddedos-org#90's gate; the gate did not wait for it.

CI plumbing:
- eosim-sanity.yml: the install-validate job is written in bash but ran under
  PowerShell on the Windows legs (no shell:), where SITE_PACKAGES=$(...) is an
  unknown command and `|| { exit 1 }` is an unexecuted script block.
- scorecard.yml: ossf/scorecard-action@v2.4.0 pulls gcr.io, which now demands
  GCP billing. v2.4.3 pulls ghcr.io; eos already pins it and is green.

Verified locally (macOS, clang): Release build clean, 31/31 ctest; the same
under -DEBLDR_SANITIZE=ON (ASan+UBSan); 78/78 pytest.

Not fixed here, reported separately: core/keystore.c's compiled-in
default_dev_key is described as the RFC 8032 TEST 1 public key but differs
from byte 21 on and is not a point on the curve, so nothing can verify
against it on any board without OTP. With embeddedos-org#104 that makes firmware update
refuse every image on such boards.
Kartikey1306 added a commit to Kartikey1306/eBoot that referenced this pull request Sep 14, 2026
…harnesses

Answers the second review on embeddedos-org#84.

Finding 2 (Medium) -- eos_fdt_validate() and eos_fdt_get_prop() kept an
out-of-bounds read by design. Both dereferenced hdr->totalsize before any
length was known and handed that attacker-controlled value to the _sized form
as its bound, so calling either on a short buffer read past it before a single
check had run. The header called that a caller warrant; a warrant is not a
check, and it is the exact bug this PR exists to fix. Neither had an in-tree
caller.

Removed rather than documented. There is now one form of each entry point and
it always takes the length:

    int eos_fdt_validate(const void *fdt_blob, uint32_t avail);
    int eos_fdt_get_prop(const void *fdt, uint32_t fdt_len, ...);

An exported unsafe twin in a TCB header is a future boot-path caller
reintroducing the bug with no compiler complaint, which is worth more than the
convenience of a one-argument call. eos_fdt_load() already passed max_size.
The test that pinned the wrapper's behaviour is gone with the wrapper, and
get_prop_sized_exact() collapsed into get_prop_exact() since they became the
same function.

Finding 3 (Medium) -- tests/fuzz/ was built by nothing. EBLDR_BUILD_FUZZ
defaults OFF and no job set it, so the harness added here joined five others
that no CI job compiles. A harness that is never built cannot fail to build,
which is how fuzz_devicetree came to declare a function that did not exist and
sit there unnoticed (eos#50).

Adds a `fuzz-build` job: configure with clang, build every harness, and run
each for five seconds over its own generated inputs. That is not a campaign --
it is enough to catch a harness that no longer compiles or crashes at once,
which is the failure this repo has actually had. Note it needs
EBLDR_BUILD_TESTS=ON as well: tests/fuzz/ is added from tests/CMakeLists.txt,
so EBLDR_BUILD_FUZZ alone configures cleanly and builds no harness at all --
the job would have passed having compiled nothing. Found that locally before
writing the job, not after.

  NOT RUN, and this is the honest limit: this host has no libFuzzer runtime
  (libclang_rt.fuzzer_osx.a is absent from the Xcode toolchain), so the link
  step cannot be reproduced here for any harness, old or new. What I verified
  is that CMake configures with both flags and reports all six targets --
  "Fuzz targets: fuzz_image_verify, fuzz_recovery_protocol, fuzz_fw_update,
  fuzz_crypto, fuzz_bootctl, fuzz_fdt" -- and that fuzz_fdt.c passes
  `cc -fsyntax-only`. The link and the smoke run are CI's to show, and this
  job is what makes them visible.

  Coordination note: embeddedos-org#90 adds a `CI Gate` whose needs list is
  [test, build-arm, static-analysis]. Whichever of embeddedos-org#84 and embeddedos-org#90 lands second
  must add fuzz-build to that list -- and embeddedos-org#90's own
  test_gate_covers_every_job_that_runs_on_a_pull_request fails loudly if it is
  not, which is the guard working rather than a trap.

Finding 1 (High) is a PR-body correction, made there: the diff carries embeddedos-org#94's
master repair because this branch is stacked on it, and the body described
only the FDT parser.

Verified:
  ctest                                    22/22 PASS
  pytest tests/                            38 passed
  test_fdt_loader                          13 tests PASS
  grep for a length-free entry point       none remains in the header

Refs embeddedos-org#84
Kartikey1306 added a commit to Kartikey1306/eBoot that referenced this pull request Sep 14, 2026
… clash

Three findings from the review on embeddedos-org#80, all in files this branch already owns.

Finding 2 (Medium) -- core/fw_decrypt.c's file header still read "Falls back
to HAL hw_aes_decrypt if available." The diff started at line 192, so that
line survived and directly contradicted the twenty-line rationale this PR
installs below it. A self-contradictory file is worse than the original.

Finding 1 (Medium) -- after the removal, hw_aes_decrypt has zero call sites
while eos_hal.h still advertises it under "software fallback used if NULL",
which is now false in the other direction: a board author who implements the
hook gets nothing, silently, with no diagnostic. That is the same class of
failure this PR is fixing. Kept the member rather than deleting it -- removing
it from a public struct is an ABI change for out-of-tree boards, and the hook
is worth having once it can express the operation -- and documented it as
reserved and currently unconsumed, with the reason and with what a
streaming-capable replacement would need.

Finding 3 (Low) -- this PR and embeddedos-org#82 both inserted their add_executable/add_test
triple immediately after add_test(NAME test_keystore ...), so whichever landed
second would have conflicted for no reason but placement. Re-anchored this
one to the end of the registrations, with a comment saying why.

Also rebased: this branch was 7 commits behind and its diff against current
master would have reverted the test_recovery link-line fix. It is now stacked
on embeddedos-org#94, which repairs master -- without that, every PR that builds the test
suite is red on include/eos_image.h and core/ed25519_verify.c.

Verified:
  cmake --build (EBLDR_BUILD_TESTS=ON)   clean
  ctest                                  22/22 PASS
  test_fw_decrypt                        8/8 PASS
  git grep hw_aes_decrypt                header + this file's comment only

Refs embeddedos-org#80
Kartikey1306 added a commit to Kartikey1306/eBoot that referenced this pull request Sep 14, 2026
… makes

Answers the second review on embeddedos-org#82.

Finding 1 (High) -- step 4, "Verify signing key against OTP root-of-trust",
was the same fail-open this PR removes from step 7, two steps earlier. An
`eos_hal_otp_read()` failure was discarded and boot continued; and when the
read succeeded and the anchor was provisioned, the body of the `if` was
`/* In a full implementation, extract key hash from TLV and compare */`. So a
device whose root of trust *is* provisioned booted an image signed by any key
the image carried, and step 8 recorded EOS_SBOOT_OK.

Implementing the TLV comparison is out of scope, as the review says. The two
things that are in scope are done: a non-EOS_OK otp_read now fails
EOS_SBOOT_ERR_SIGNATURE, and a provisioned anchor that nothing compares
against refuses the boot rather than proceeding. An unprovisioned board
(all-zero anchor) is deliberately unchanged -- there is nothing to check
against, and refusing would brick every board that has not been provisioned.
The comment now states plainly that the step is planned rather than
implemented, which §8.1 asks for and a comment inside an `if` was not.

  No test for those two refusals, deliberately, and the file says why rather
  than leaving it to be discovered. Reaching step 4 requires passing step 3 --
  a real Ed25519 signature checked against the keystore. I wrote the obvious
  test first and it was worthless: with require_signature = true and an
  unsigned fixture the boot fails at step 3 and returns the same
  EOS_SBOOT_ERR_SIGNATURE step 4 returns, so it passed against the unfixed
  code too. I confirmed that by reverting step 4 and watching it still pass.
  A test that cannot fail is worse than none. What is there instead is the
  counter-check that the change does not refuse a boot it should allow.

  The fixture is buildable -- the keystore ships RFC 8032 TEST 1's public key
  and the matching private key is in the RFC -- but that machinery is embeddedos-org#88's
  (tools/gen_signed_image_fixture.py). Worth doing once embeddedos-org#88 lands.

Finding 3 (Low) -- `TEST()` did not increment `tests_run` and `main()`
hardcoded `tests_run = 6`, so a test added to the file but not wired into
`main()` would have been skipped with a zero exit. embeddedos-org#94 removed exactly this
from tests/unit/test_ed25519.c, where a hardcoded 11 was masking two uncalled
tests. Same fix here.

Finding 4 (Low) -- the Valgrind `foreach` is hand-maintained and missed 6 of
22 registered tests. Added test_secure_boot_policy, test_fdt_loader and
test_fw_decrypt. The list being hand-maintained at all is the real defect and
is not fixed here -- it is the same class as the hardcoded count, one level
up.

Finding 2 (Medium), that eos_secure_boot() has no production caller, stands
and is not addressed here; finding 1 makes it sharper rather than resolving
it. Finding 5 (Low) is a PR-body correction.

Verified:
  ctest                          22/22 PASS
  test_secure_boot_policy        7/7 PASS
  step 7 discrimination, still: reverting the step-7 branch fails
    test_secure_boot_refuses_when_the_debug_lock_cannot_be_taken

Refs embeddedos-org#82
Kartikey1306 added a commit to Kartikey1306/eBoot that referenced this pull request Sep 15, 2026
Twenty PRs were merged into master in ninety minutes on 09-07, each on the
base it was written against. Master has not configured, compiled, linked or
passed its tests since. Every nightly and every eos simulation run (which
builds eBoot master) has been red for the same reason.

Configure:
- tests/CMakeLists.txt registered eboot_test_fdt_loader twice. embeddedos-org#84 added it,
  and embeddedos-org#85 -- stacked on embeddedos-org#84 -- re-added it at a different anchor when it was
  replayed onto a master that already had embeddedos-org#84. Same hunk as embeddedos-org#111.

Compile (eboot_core):
- embeddedos-org#55 restored a core/sha512.c from 02b7dac that keeps its byte count in
  ctx->count; the eos_sha512_ctx_t master ships has bitlen[2]/buffer_len
  (embeddedos-org#69/embeddedos-org#93). Back to the pre-embeddedos-org#55 file, blob-identical (d9aa57c).
- embeddedos-org#55's source-list "correction" dropped core/boot_log.c, core/secure_boot.c
  and core/fdt_loader.c, which embeddedos-org#72/embeddedos-org#84 had added after embeddedos-org#55 was written.
  CMakeLists.txt is blob-identical to pre-embeddedos-org#55 again (f8fe6eb).
- embeddedos-org#55 replaced the eos_boot_log_get_head() declaration with a second copy of
  eos_boot_log_read(); embeddedos-org#91 had already fixed the prototype it meant to fix.
  Header restored (964ebb8).
- embeddedos-org#94 and embeddedos-org#105 each repaired the Ed25519 verifier and each added an identical
  static scalarbase(); both merged. One copy removed.
- The same pair each added k_low_order[]/messages[] to test_ed25519.c. The
  embeddedos-org#105 copy is removed; embeddedos-org#94's stays because it also carries k_non_canonical[].

Tests that stopped passing because two merged PRs disagree on behaviour:
- embeddedos-org#104 verifies the image signature at install unconditionally, before the
  anti-rollback check embeddedos-org#103 added, so embeddedos-org#103's unsigned images are refused as
  EOS_ERR_SIGNATURE before they can be refused as EOS_ERR_ANTI_ROLLBACK, and
  test_fw_transport's XMODEM install can no longer finalize. Both suites now
  stream genuinely signed images. eBoot has no Ed25519 signer in C, so
  tools/gen_fw_update_test_sigs.py signs the exact header prefixes those
  suites build under the RFC 8032 section 7.1 TEST 1 key and emits
  tests/vectors/fw_update_test_sigs.h; the suites serve that key from a
  simulated OTP slot 0. Negative control: one flipped signature byte fails
  test_write_streams_tlv_then_finalize_rejects_below_floor with
  EOS_ERR_SIGNATURE.
- embeddedos-org#103's step 5b reads the TLV counter through the HAL slot containing the
  image; test_secure_boot_policy (embeddedos-org#82) declared no slots, so eos_secure_boot()
  returned EOS_SBOOT_ERR_BAD_HEADER two steps before the one under test. The
  fixture now places its image in slot A.

Guards from embeddedos-org#95 that later merges walked back, never run until now because the
C configure step failed first:
- embeddedos-org#103 replayed the hand-written Valgrind foreach over the derived one.
  Restored foreach(TEST_NAME ${EBLDR_UNIT_TESTS}); eleven registered suites
  had no list(APPEND ...) and so no Valgrind run.
- Seven suites assign tests_run = <literal> and their TEST() does not count;
  four suites have no TEST() macro at all. Counted, and classified.
- embeddedos-org#101 added fuzz-build after embeddedos-org#90's gate; the gate did not wait for it.

CI plumbing:
- eosim-sanity.yml: the install-validate job is written in bash but ran under
  PowerShell on the Windows legs (no shell:), where SITE_PACKAGES=$(...) is an
  unknown command and `|| { exit 1 }` is an unexecuted script block.
- scorecard.yml: ossf/scorecard-action@v2.4.0 pulls gcr.io, which now demands
  GCP billing. v2.4.3 pulls ghcr.io; eos already pins it and is green.

Verified locally (macOS, clang): Release build clean, 31/31 ctest; the same
under -DEBLDR_SANITIZE=ON (ASan+UBSan); 78/78 pytest.

Not fixed here, reported separately: core/keystore.c's compiled-in
default_dev_key is described as the RFC 8032 TEST 1 public key but differs
from byte 21 on and is not a point on the curve, so nothing can verify
against it on any board without OTP. With embeddedos-org#104 that makes firmware update
refuse every image on such boards.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants