Skip to content

Commit 94f97ab

Browse files
Florian Gaultieragix
authored andcommitted
Prevent import table overwritting by shifting entry point
1 parent e269c1e commit 94f97ab

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

lib/msf/util/exe.rb

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -314,20 +314,18 @@ def self.to_winpe_only(framework, code, opts={}, arch="x86")
314314
}
315315

316316
pe_header_size = 0x18
317+
entryPoint_offset = 0x28
317318
section_size = 0x28
318319
characteristics_offset = 0x24
319320
virtualAddress_offset = 0x0c
320321
sizeOfRawData_offset = 0x10
321322

322-
sections_table_rva =
323+
sections_table_offset =
323324
pe._dos_header.v['e_lfanew'] +
324325
pe._file_header.v['SizeOfOptionalHeader'] +
325326
pe_header_size
326327

327-
sections_table_offset = pe.rva_to_file_offset(sections_table_rva)
328-
329-
sections_table_characteristics_offset =
330-
pe.rva_to_file_offset(sections_table_rva + characteristics_offset)
328+
sections_table_characteristics_offset = sections_table_offset + characteristics_offset
331329

332330
sections_header = []
333331
pe._file_header.v['NumberOfSections'].times { |i|
@@ -338,15 +336,22 @@ def self.to_winpe_only(framework, code, opts={}, arch="x86")
338336
]
339337
}
340338

339+
addressOfEntryPoint = pe.hdr.opt.AddressOfEntryPoint
340+
341341
# look for section with entry point
342342
sections_header.each do |sec|
343343
virtualAddress = sec[1][virtualAddress_offset,0x4].unpack('L')[0]
344344
sizeOfRawData = sec[1][sizeOfRawData_offset,0x4].unpack('L')[0]
345345
characteristics = sec[1][characteristics_offset,0x4].unpack('L')[0]
346346

347-
if (virtualAddress...virtualAddress+sizeOfRawData).include?(pe.hdr.opt.AddressOfEntryPoint)
348-
if sizeOfRawData<code.length
349-
raise RuntimeError, "The EXE::Template doesn't contain enough place to write the payload."
347+
if (virtualAddress...virtualAddress+sizeOfRawData).include?(addressOfEntryPoint)
348+
importsTable = pe.hdr.opt.DataDirectory[8..(8+4)].unpack('L')[0]
349+
if (importsTable-addressOfEntryPoint)<code.length
350+
#shift original entry point to prevent tables overwritting
351+
addressOfEntryPoint = importsTable - (code.length + 4)
352+
353+
entry_point_offset = pe._dos_header.v['e_lfanew'] + entryPoint_offset
354+
exe[entry_point_offset,4] = [addressOfEntryPoint].pack('L')
350355
end
351356
# put this section writable
352357
characteristics |= 0x8000_0000
@@ -356,7 +361,7 @@ def self.to_winpe_only(framework, code, opts={}, arch="x86")
356361
end
357362

358363
# put the shellcode at the entry point, overwriting template
359-
entryPoint_file_offset = pe.rva_to_file_offset(pe.hdr.opt.AddressOfEntryPoint)
364+
entryPoint_file_offset = pe.rva_to_file_offset(addressOfEntryPoint)
360365
exe[entryPoint_file_offset,code.length] = code
361366
return exe
362367
end

0 commit comments

Comments
 (0)