Validate segment nsects against cmdsize and file bounds - #1026
Conversation
- Check length against available file data and that section table fits cmdsize - Raise LoadCommandSizeError on corrupt or malicious nsects values Signed-off-by: Caleb Xu <calebcenter@live.com> Assisted-by: OpenCode (Nemotron 3 Ultra)
There was a problem hiding this comment.
馃煛 Changes recommended
The security-sensitive bounds checks need regression test coverage.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds bounds validation to prevent malicious nsects values from causing excessive allocations.
Changes:
- Validates section-table length against file data and
cmdsize. - Raises
LoadCommandSizeErrorfor invalid section counts.
File summaries
| File | Review |
|---|---|
lib/macho/load_commands.rb |
Adds section-table bounds checks. Regression tests for corrupted 32-bit and 64-bit nsects values are required. |
Review details
- Files reviewed: 1/1 changed files
- Comments generated: 1
- Review effort level: Balanced
馃挕 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| length = nsects * klass.bytesize | ||
|
|
||
| available = view.raw_data.bytesize - offset | ||
| raise LoadCommandSizeError, cmdsize if length > available || self.class.bytesize + length > cmdsize |
p-linnane
left a comment
There was a problem hiding this comment.
The bounds check itself looks correct, but this security-sensitive parser change needs regression coverage before merge.
Please add tests for both LC_SEGMENT and LC_SEGMENT_64. Set nsects to one more than the number of sections permitted by cmdsize, then assert that sections raises MachO::LoadCommandSizeError. Please use the smallest invalid value rather than an enormous count, so a future regression fails safely without risking an OOM in CI.
The existing Copilot comment captures this requirement and can be resolved once those tests are added.
Separately, the same count-controlled allocation pattern exists for LC_BUILD_VERSION#ntools and LC_TWOLEVEL_HINTS#nhints. Those are pre-existing issues and do not need to expand this PR鈥檚 scope, but they should be tracked separately. Until addressed, this PR should be described specifically as fixing nsects, not malicious count handling generally.
A quick PoC script (tested on Linux, haven't checked if
rss_mbworks on macOS) which loads a modified variant of the test fixture (manipulatingnsectsto be invalidly large) and can cause a large memory allocation: