Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions lib/macho/load_commands.rb
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,9 @@ def sections
offset = view.offset + self.class.bytesize
length = nsects * klass.bytesize

available = view.raw_data.bytesize - offset
raise LoadCommandSizeError, cmdsize if length > available || self.class.bytesize + length > cmdsize
Comment thread
alebcay marked this conversation as resolved.

bins = view.raw_data[offset, length]
bins.unpack("a#{klass.bytesize}" * nsects).map do |bin|
klass.new_from_bin(view.endianness, bin)
Expand Down
30 changes: 30 additions & 0 deletions test/test_macho.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,14 @@ def test_load_command_with_invalid_string_offset
end
end

def test_segment_with_too_many_sections
assert_segment_sections_exceed_cmdsize(:i386, :LC_SEGMENT)
end

def test_segment_64_with_too_many_sections
assert_segment_sections_exceed_cmdsize(:x86_64, :LC_SEGMENT_64)
end

def test_minimal_macho
file = MachO::MachOFile.new(fixture(:yaml2obj, "minimal.macho"))

Expand Down Expand Up @@ -803,4 +811,26 @@ def test_to_h
assert_kind_of Integer, lc_hsh["structure"]["bytesize"]
end
end

private

def assert_segment_sections_exceed_cmdsize(arch, command_type)
bin = File.binread(fixture(arch, "hello.bin"))
file = MachO::MachOFile.new_from_bin(bin)
segment = file[command_type].first
section_class = if segment.is_a?(MachO::LoadCommands::SegmentCommand64)
MachO::Sections::Section64
else
MachO::Sections::Section
end
nsects = ((segment.cmdsize - segment.class.bytesize) / section_class.bytesize) + 1
nsects_offset = segment.view.offset + segment.class.bytesize - 8
bin[nsects_offset, 4] = [nsects].pack(file.endianness == :little ? "L<" : "L>")

segment = MachO::MachOFile.new_from_bin(bin)[command_type].first

assert_raises MachO::LoadCommandSizeError do
segment.sections
end
end
end