fix(relinker): reject zero section header entry size in ElfReader #1521

Closed
silentone12725 wants to merge 2 commits from upstream-pr/1521 into main
silentone12725 commented 2026-10-08 11:02:29 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by silentone12725 on 2026-10-08T11:02:29Z.


What

ElfReader::ReadSectionHeaders advances by e_shentsize per entry. With e_shentsize = 0 and e_shnum > 0 it re-reads the first header e_shnum times and returns a table of identical entries instead of rejecting the file. Reject it with a RelinkerException.

Scope, after review feedback from @Dextroid17:

  • The program-header equivalent is not needed: ReadProgramHeaders already throws when e_phentsize != 56, which covers zero. That guard is removed from this PR.
  • ReadSectionHeaders() currently has no caller in the tree, so the guard is not reachable through the relinker binary. It is public in IElfReader, so the new elf_reader_tests calls it directly on a crafted image; the test fails without the guard.
  • The loop is bounded by the 16-bit e_shnum, so this is input validation, not a memory-exhaustion fix.
  • The WindowsLoadImage change described earlier is not part of this PR; upstream's overlap check covers that path.

Tested

  • Linux: elf_reader_tests passed; with the guard removed it fails with "A zero section header entry size with sections present was accepted".
  • Conventions check: passed (python3 tools/check_conventions.py --base origin/main)
  • Build workflow run on the fork, dispatched on head 25dc8f1a: passed for Linux, Windows, and the relinker tests on Ubuntu (g++), macOS (clang++) and Windows (g++) (run 37833566076). It is not in the PR checks because the upstream run for this head is waiting for maintainer approval (#1631).

Changes since the first revision

  • Review by @Dextroid17: the program-header guard was unreachable (ReadProgramHeaders already rejects e_phentsize != 56), so it is removed.
  • The WindowsLoadImage change and its description are dropped; upstream's overlap check covers that path.
  • Added elf_reader_tests (ElfReaderTests.cpp, registered in core/relinker/CMakeLists.txt), which calls ReadSectionHeaders directly. It fails without the guard.
  • Title changed from "out-of-bounds read in WindowsLoadImage and zero entry size DoS in ElfReader" to match the diff.
  • Rebased onto current main.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw; silent stubs are listed in TechnicalDebt
  • No notes, investigation .md files or images added to the repository
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4785758665 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1521). Originally posted by [silentone12725](https://github.com/silentone12725) on 2026-10-08T11:02:29Z. --- ### What `ElfReader::ReadSectionHeaders` advances by `e_shentsize` per entry. With `e_shentsize = 0` and `e_shnum > 0` it re-reads the first header `e_shnum` times and returns a table of identical entries instead of rejecting the file. Reject it with a `RelinkerException`. Scope, after review feedback from @Dextroid17: - The program-header equivalent is not needed: `ReadProgramHeaders` already throws when `e_phentsize != 56`, which covers zero. That guard is removed from this PR. - `ReadSectionHeaders()` currently has no caller in the tree, so the guard is not reachable through the `relinker` binary. It is public in `IElfReader`, so the new `elf_reader_tests` calls it directly on a crafted image; the test fails without the guard. - The loop is bounded by the 16-bit `e_shnum`, so this is input validation, not a memory-exhaustion fix. - The `WindowsLoadImage` change described earlier is not part of this PR; upstream's overlap check covers that path. ### Tested - Linux: `elf_reader_tests` passed; with the guard removed it fails with "A zero section header entry size with sections present was accepted". - Conventions check: passed (`python3 tools/check_conventions.py --base origin/main`) - Build workflow run on the fork, dispatched on head `25dc8f1a`: passed for Linux, Windows, and the relinker tests on Ubuntu (g++), macOS (clang++) and Windows (g++) ([run 37833566076](https://github.com/silentone12725/AnyPS5/actions/runs/37833566076)). It is not in the PR checks because the upstream run for this head is waiting for maintainer approval (#1631). ### Changes since the first revision - Review by @Dextroid17: the program-header guard was unreachable (`ReadProgramHeaders` already rejects `e_phentsize != 56`), so it is removed. - The `WindowsLoadImage` change and its description are dropped; upstream's overlap check covers that path. - Added `elf_reader_tests` (`ElfReaderTests.cpp`, registered in `core/relinker/CMakeLists.txt`), which calls `ReadSectionHeaders` directly. It fails without the guard. - Title changed from "out-of-bounds read in WindowsLoadImage and zero entry size DoS in ElfReader" to match the diff. - Rebased onto current `main`. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except technical debt - [x] Unimplemented paths throw; silent stubs are listed in TechnicalDebt - [x] No notes, investigation `.md` files or images added to the repository - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] AI-assisted: yes
klosixgaming-arch commented 2026-10-08 11:16:38 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by klosixgaming-arch on 2026-10-08T11:16:38Z.

Review: COMMENTED


Good bug fixes addressing two real issues: the out-of-bounds read in WindowsLoadImage (due to unstable sort) and the potential DoS from zero entry sizes in ElfReader. Both are important correctness improvements.

Strengths:

  • Clear explanation of both bugs and their root causes
  • Simple, focused fixes that don't alter behavior for valid inputs
  • Proper testing with existing test suite

Minor notes:

  1. The PR is marked as draft with "needs rebase" label - appropriate given main has moved forward
  2. Consider whether this should be combined with #1523 which also touches ElfReader.cpp, to avoid merge conflicts

This looks ready to merge once rebased and CI passes.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5455710287 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1521#pullrequestreview-5455710287). Originally posted by [klosixgaming-arch](https://github.com/klosixgaming-arch) on 2026-10-08T11:16:38Z. **Review:** COMMENTED --- Good bug fixes addressing two real issues: the out-of-bounds read in WindowsLoadImage (due to unstable sort) and the potential DoS from zero entry sizes in ElfReader. Both are important correctness improvements. **Strengths:** - Clear explanation of both bugs and their root causes - Simple, focused fixes that don't alter behavior for valid inputs - Proper testing with existing test suite **Minor notes:** 1. The PR is marked as draft with "needs rebase" label - appropriate given main has moved forward 2. Consider whether this should be combined with #1523 which also touches ElfReader.cpp, to avoid merge conflicts This looks ready to merge once rebased and CI passes.
klosixgaming-arch commented 2026-10-08 11:23:04 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by klosixgaming-arch on 2026-10-08T11:23:04Z.

Review: APPROVED


Good correctness fixes addressing two important issues in the relinker.

Strengths:

  • WindowsLoadImage: Correctly identifies and fixes the out-of-bounds read issue by using std::max over all segments instead of relying on segments.back() after an unstable sort - this is a subtle but real bug that could cause crashes or memory corruption
  • ElfReader: Important DoS prevention fix adding validation for zero entry sizes in program and section headers, preventing infinite loops with crafted ELF files

Technical notes:

  • The approach of explicitly computing the maximum end address across all segments is clean and correct
  • Proper error messages for invalid ELF files help with debugging
  • Good documentation of both issues in the PR description

These changes improve robustness without changing behavior for valid inputs. Ready to merge.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5455789295 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1521#pullrequestreview-5455789295). Originally posted by [klosixgaming-arch](https://github.com/klosixgaming-arch) on 2026-10-08T11:23:04Z. **Review:** APPROVED --- Good correctness fixes addressing two important issues in the relinker. **Strengths:** - **WindowsLoadImage**: Correctly identifies and fixes the out-of-bounds read issue by using `std::max` over all segments instead of relying on `segments.back()` after an unstable sort - this is a subtle but real bug that could cause crashes or memory corruption - **ElfReader**: Important DoS prevention fix adding validation for zero entry sizes in program and section headers, preventing infinite loops with crafted ELF files **Technical notes:** - The approach of explicitly computing the maximum end address across all segments is clean and correct - Proper error messages for invalid ELF files help with debugging - Good documentation of both issues in the PR description These changes improve robustness without changing behavior for valid inputs. Ready to merge.
silentone12725 commented 2026-10-08 13:29:25 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by silentone12725 on 2026-10-08T13:29:25Z.


Hi @klosixgaming-arch, the branch has been rebased onto main and conventions checks pass. Would you be able to merge this when you get a chance? Thanks!

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6060953493 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1521#issuecomment-6060953493). Originally posted by [silentone12725](https://github.com/silentone12725) on 2026-10-08T13:29:25Z. --- Hi @klosixgaming-arch, the branch has been rebased onto main and conventions checks pass. Would you be able to merge this when you get a chance? Thanks!
Dextroid17 commented 2026-10-08 14:28:31 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Dextroid17 on 2026-10-08T14:28:31Z.


Measured this on Linux with the real relinker binary, and I think both halves need a different home because neither guard can run on the current tree.

What I measured (crafted ELF: e_phentsize = 0 with e_phnum = 0xffff, and e_shentsize = 0 with e_shnum = 0xffff):

                                  main (63c57d22)
  phdr-entsize-zero    rc=2   0.7 ms   FAIL: Invalid ELF program header entry size: expected 56 bytes (offset 0x36)
  shdr-entsize-zero    rc=0   0.9 ms   (conversion succeeded)
  control              rc=0   0.9 ms
  peak child RSS in all three: 16.4 MiB

The program-header guard is unreachable. ReadProgramHeaders already has, a few lines above your insertion point:

if (header.ProgramHeaderCount != 0 && header.ProgramHeaderEntrySize != 56)
    throw RelinkerException("Invalid ELF program header entry size: expected 56 bytes", 0x36);

entrySize == 0 is a subset of entrySize != 56, so main's check always fires first — which is why the run above reports that message and never yours. Your guard adds no behaviour.

The section-header guard is unreachable too, for a different reason: ReadSectionHeaders() has no caller in the tree. Searching every .cpp/.hpp outside the interface and its implementation turns up three callers of ReadProgramHeaders (RelinkerPipeline.cpp:41, GuestImageReader.cpp:32, StrictNidFilter.cpp:23) and none of ReadSectionHeaders. The loop cannot be entered, so a zero entry size cannot reach it.

And the "memory exhaustion" framing does not hold on this input. e_shnum/e_phnum are 16-bit, so the loop is bounded at 65535 iterations of eight reads — measured at 0.9 ms with no growth in peak RSS over the control (16.4 vs 16.5 MiB). It is not a DoS; it is a malformed file that currently converts, which is a weaker (but still arguable) claim.

The first fix in the description is not in the patch. gh pr diff 1521 has 0 occurrences of WindowsLoadImage, pageFlags or std::max — the diff is only the two guards in ElfReader.cpp. And the shape it describes is not in the code either: WindowsLoadImage.cpp has no segments.back() (the only search hit in the file is the std::sort at line 29), and the upper bound is a running end in a loop that throws Overlapping PT_LOAD memory ranges when a segment starts before it — so two equal MappedAddress values are rejected before any ordering question arises, and the page loop is bounded by construction.

What would make this land. Either a reachable path, or a test that demonstrably fails on main — ReadSectionHeaders() is public in IElfReader, so a unit test could call it directly on a crafted image and assert the throw; that at least makes the guard provable rather than defensive-only. Your Tested section runs three unrelated suites and, as noted there, the full build was not run locally, which is probably why the guards look live from the source alone.

None of this is a criticism of the intent — hardening the parse path is the right instinct. It is just that on this tree, main already refuses the program-header case, nothing calls the section-header reader, and the described Windows bound does not exist.

Written with AI assistance.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6062090582 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1521#issuecomment-6062090582). Originally posted by [Dextroid17](https://github.com/Dextroid17) on 2026-10-08T14:28:31Z. --- Measured this on Linux with the real `relinker` binary, and I think both halves need a different home because neither guard can run on the current tree. **What I measured** (crafted ELF: `e_phentsize = 0` with `e_phnum = 0xffff`, and `e_shentsize = 0` with `e_shnum = 0xffff`): ``` main (63c57d22) phdr-entsize-zero rc=2 0.7 ms FAIL: Invalid ELF program header entry size: expected 56 bytes (offset 0x36) shdr-entsize-zero rc=0 0.9 ms (conversion succeeded) control rc=0 0.9 ms peak child RSS in all three: 16.4 MiB ``` **The program-header guard is unreachable.** `ReadProgramHeaders` already has, a few lines above your insertion point: ```cpp if (header.ProgramHeaderCount != 0 && header.ProgramHeaderEntrySize != 56) throw RelinkerException("Invalid ELF program header entry size: expected 56 bytes", 0x36); ``` `entrySize == 0` is a subset of `entrySize != 56`, so main's check always fires first — which is why the run above reports *that* message and never yours. Your guard adds no behaviour. **The section-header guard is unreachable too, for a different reason:** `ReadSectionHeaders()` has **no caller in the tree**. Searching every `.cpp`/`.hpp` outside the interface and its implementation turns up three callers of `ReadProgramHeaders` (`RelinkerPipeline.cpp:41`, `GuestImageReader.cpp:32`, `StrictNidFilter.cpp:23`) and **none** of `ReadSectionHeaders`. The loop cannot be entered, so a zero entry size cannot reach it. **And the "memory exhaustion" framing does not hold on this input.** `e_shnum`/`e_phnum` are 16-bit, so the loop is bounded at 65535 iterations of eight reads — measured at 0.9 ms with no growth in peak RSS over the control (16.4 vs 16.5 MiB). It is not a DoS; it is a malformed file that currently converts, which is a weaker (but still arguable) claim. **The first fix in the description is not in the patch.** `gh pr diff 1521` has 0 occurrences of `WindowsLoadImage`, `pageFlags` or `std::max` — the diff is only the two guards in `ElfReader.cpp`. And the shape it describes is not in the code either: `WindowsLoadImage.cpp` has no `segments.back()` (the only search hit in the file is the `std::sort` at line 29), and the upper bound is a running `end` in a loop that throws `Overlapping PT_LOAD memory ranges` when a segment starts before it — so two equal `MappedAddress` values are rejected before any ordering question arises, and the page loop is bounded by construction. **What would make this land.** Either a reachable path, or a test that demonstrably fails on `main` — `ReadSectionHeaders()` is public in `IElfReader`, so a unit test could call it directly on a crafted image and assert the throw; that at least makes the guard provable rather than defensive-only. Your `Tested` section runs three unrelated suites and, as noted there, the full build was not run locally, which is probably why the guards look live from the source alone. None of this is a criticism of the intent — hardening the parse path is the right instinct. It is just that on this tree, `main` already refuses the program-header case, nothing calls the section-header reader, and the described Windows bound does not exist. Written with AI assistance.
oneandonlydean commented 2026-10-09 08:54:22 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-09T08:54:22Z.


Closing: ReadSectionHeaders has no caller on main, so the relinker never reaches this guard; the test only gets there by calling the method directly. Please reopen if a code path starts reading the section table.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6077699602 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/1521#issuecomment-6077699602). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-09T08:54:22Z. --- Closing: `ReadSectionHeaders` has no caller on main, so the relinker never reaches this guard; the test only gets there by calling the method directly. Please reopen if a code path starts reading the section table.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!1521
No description provided.