code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def encode(coff) opth = super(coff) DIRECTORIES[0, @numrva].each { |d| if d = coff.directory[d] d = d.dup d[0] = Expression[d[0], :-, coff.label_at(coff.encoded, 0)] if d[0].kind_of?(::String) else d = [0, 0] end opth << coff.encode_word(d[0]) << coff.encode_word(d[1]) } opt...
encodes an Optional header and the directories
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def set_default_values(coff) @signature ||= (coff.bitsize == 64 ? 'PE+' : 'PE') @link_ver_maj ||= 1 @link_ver_min ||= 0 @sect_align ||= 0x1000 align = lambda { |sz| EncodedData.align_size(sz, @sect_align) } @code_size ||= coff.sections.find_all { |s| s.characteristics.include? 'CONTAINS_CODE' ...
find good default values for optheader members, based on coff.sections
set_default_values
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def set_default_values(coff) @name ||= '' @virtsize ||= @encoded.virtsize @virtaddr ||= Expression[coff.label_at(@encoded, 0, 'sect_start'), :-, coff.label_at(coff.encoded, 0)] @rawsize ||= coff.new_label('sect_rawsize') @rawaddr ||= coff.new_label('sect_rawaddr') super(coff) end
find good default values for section header members, defines rawaddr/rawsize as new_label for later fixup
set_default_values
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode(coff, edata) edata['iat'] << EncodedData.new # edata['ilt'] = edata['iat'] label = lambda { |n| coff.label_at(edata[n], 0, n) } rva_end = lambda { |n| Expression[[label[n], :-, coff.label_at(coff.encoded, 0)], :+, edata[n].virtsize] } @libname_p = rva_end['nametable'] @ilt_p = rva_end['ilt...
encode one import directory + iat + names in the edata hash received as arg
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_exports edata = @export.encode self # must include name tables (for forwarders) @directory['export_table'] = [label_at(edata, 0, 'export_table'), edata.virtsize] s = Section.new s.name = '.edata' s.encoded = edata s.characteristics = %w[MEM_READ] encode_append_section s end
encodes the export table as a new section, updates directory['export_table']
encode_exports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_imports idata, iat = ImportDirectory.encode(self, @imports) @directory['import_table'] = [label_at(idata, 0, 'idata'), idata.virtsize] s = Section.new s.name = '.idata' s.encoded = idata s.characteristics = %w[MEM_READ MEM_WRITE MEM_DISCARDABLE] encode_append_section s if @imports.first an...
encodes the import tables as a new section, updates directory['import_table'] and directory['iat']
encode_imports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_relocs if @relocations.empty? rt = RelocationTable.new rt.base_addr = 0 rt.relocs = [] @relocations << rt end relocs = @relocations.inject(EncodedData.new) { |edata, rt_| edata << rt_.encode(self) } @directory['base_relocation_table'] = [label_at(relocs, 0, 'reloc_table'), relocs.virtsiz...
encodes relocation tables in a new section .reloc, updates @directory['base_relocation_table']
encode_relocs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def create_relocation_tables @relocations = [] # create a fake binding with all exports, to find only-image_base-dependant relocs targets # not foolproof, but works in standard cases startaddr = curaddr = label_at(@encoded, 0, 'coff_start') binding = {} @sections.each { |s| binding.update s.encoded.bind...
creates the @relocations from sections.encoded.reloc
create_relocation_tables
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def pre_encode_header(target='exe', want_relocs=true) target = {:bin => 'exe', :lib => 'dll', :obj => 'obj', 'sys' => 'kmod', 'drv' => 'kmod'}.fetch(target, target) @header.machine ||= case @cpu.shortname when 'x64'; 'AMD64' when 'ia32'; 'I386' end @optheader.signature ||= case @cpu.size when 32;...
initialize the header from target/cpu/etc, target in ['exe' 'dll' 'kmod' 'obj']
pre_encode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def invalidate_header # set those values to nil, they will be # recomputed during encode_header [:code_size, :data_size, :udata_size, :base_of_code, :base_of_data, :sect_align, :file_align, :image_size, :headers_size, :checksum].each { |m| @optheader.send("#{m}=", nil) } [:num_sect, :ptr_sym, :num_sym, :size...
resets the values in the header that may have been modified by your script (eg section count, size, imagesize, etc) call this whenever you decode a file, modify it, and want to reencode it later
invalidate_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_header # encode section table, add CONTAINS_* flags from other characteristics flags s_table = EncodedData.new @sections.each { |s| if s.characteristics.kind_of? Array and s.characteristics.include? 'MEM_READ' if s.characteristics.include? 'MEM_EXECUTE' s.characteristics |= ['CONTAINS_CODE...
appends the header/optheader/directories/section table to @encoded
encode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_sections_fixup if @optheader.headers_size.kind_of?(::String) @encoded.fixup! @optheader.headers_size => @encoded.virtsize @optheader.headers_size = @encoded.virtsize end @encoded.align @optheader.file_align baseaddr = @optheader.image_base.kind_of?(::Integer) ? @optheader.image_base : 0x400000...
append the section bodies to @encoded, and link the resulting binary
encode_sections_fixup
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode(target='exe', want_relocs=true) @encoded = EncodedData.new label_at(@encoded, 0, 'coff_start') pre_encode_header(target, want_relocs) autoimport encode_exports if export encode_imports if imports encode_resource if resource encode_tls if tls create_relocation_tables if want_relocs encode_...
encode a COFF file, building export/import/reloc tables if needed creates the base relocation tables (need for references to IAT not known before) defaults to generating relocatable files, eg ALSR-aware pass want_relocs=false to avoid the file overhead induced by this
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def read_c_attrs(cp) cp.toplevel.symbol.each_value { |v| next if not v.kind_of? C::Variable if v.has_attribute 'export' or ea = v.has_attribute_var('export_as') @export ||= ExportDirectory.new @export.exports ||= [] e = ExportDirectory::Export.new begin e.ordinal = Integer(ea || v.name) ...
honors C attributes: export, export_as(foo), import_from(kernel32), entrypoint import by ordinal: extern __stdcall int anyname(int) __attribute__((import_from(ws2_32:28))); can alias imports with int mygpaddr_alias() attr(import_from(kernel32:GetProcAddr))
read_c_attrs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def autoimport(fallback_append='A') WindowsExports rescue return # autorequire autoexports = WindowsExports::EXPORT.dup @sections.each { |s| next if not s.encoded s.encoded.export.keys.each { |e| autoexports.delete e } } @sections.each { |s| next if not s.encoded s.encoded.reloc.each_value { |r| ...
try to resolve automatically COFF import tables from self.sections.encoded.relocations and WindowsExports::EXPORT if the relocation target is '<symbolname>' or 'iat_<symbolname>, link to the IAT address, if it is '<symbolname> + <expr>', link to a thunk (plt-like) if the relocation is not found, try again after appendi...
autoimport
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def addr_to_off(addr) s = @segments.find { |s_| s_.type == 'LOAD' and s_.vaddr <= addr and s_.vaddr + s_.memsz > addr } if addr addr - s.vaddr + s.offset if s end
transforms a virtual address to a file offset, from mmaped segments addresses
addr_to_off
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def addr_to_fileoff(addr) la = module_address la = (la == 0 ? (@load_address ||= 0) : 0) addr_to_off(addr - la) end
memory address -> file offset handles relocated LoadedELF
addr_to_fileoff
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def fileoff_to_addr(foff) if s = @segments.find { |s_| s_.type == 'LOAD' and s_.offset <= foff and s_.offset + s_.filesz > foff } la = module_address la = (la == 0 ? (@load_address ||= 0) : 0) s.vaddr + la + foff - s.offset end end
file offset -> memory address handles relocated LoadedELF
fileoff_to_addr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def add_label(name, addr) if not o = addr_to_off(addr) puts "W: Elf: #{name} points to unmmaped space #{'0x%08X' % addr}" if $VERBOSE else l = new_label(name) @encoded.add_export l, o end l end
make an export of +self.encoded+, returns the label name if successful
add_label
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_header(off = 0, decode_phdr=true, decode_shdr=true) @encoded.ptr = off @header.decode self raise InvalidExeFormat, "Invalid elf header size: #{@header.ehsize}" if Header.size(self) != @header.ehsize if decode_phdr and @header.phoff != 0 decode_program_header(@header.phoff+off) end if decode_sh...
decodes the elf header, section & program header
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_section_header(off = @header.shoff) raise InvalidExeFormat, "Invalid elf section header size: #{@header.shentsize}" if Section.size(self) != @header.shentsize @encoded.add_export new_label('section_header'), off @encoded.ptr = off @sections = [] @header.shnum.times { @sections << Section.decode(sel...
decodes the section header section names are read from shstrndx if possible
decode_section_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_program_header(off = @header.phoff) raise InvalidExeFormat, "Invalid elf program header size: #{@header.phentsize}" if Segment.size(self) != @header.phentsize @encoded.add_export new_label('program_header'), off @encoded.ptr = off @segments = [] @header.phnum.times { @segments << Segment.decode(sel...
decodes the program header table marks the elf entrypoint as an export of +self.encoded+
decode_program_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def check_symbols_hash(off = @tag['HASH']) return if not @encoded.ptr = off hash_bucket_len = decode_word sym_count = decode_word hash_bucket = [] ; hash_bucket_len.times { hash_bucket << decode_word } hash_table = [] ; sym_count.times { hash_table << decode_word } @symbols.each { |s| next if not s.na...
read the dynamic symbols hash table, and checks that every global and named symbol is accessible through it outputs a warning if it's not and $VERBOSE is set
check_symbols_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def check_symbols_gnu_hash(off = @tag['GNU_HASH'], just_get_count=false) return if not @encoded.ptr = off # when present: the symndx first symbols are not sorted (SECTION/LOCAL/FILE/etc) symtable[symndx] is sorted (1st sorted symbol) # the sorted symbols are sorted by [gnu_hash_symbol_name(symbol.name) % hash_bu...
checks every symbol's accessibility through the gnu_hash table
check_symbols_gnu_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_tags_interpret if @tag['STRTAB'] if not sz = @tag['STRSZ'] puts "W: Elf: no string table size tag" if $VERBOSE else if l = add_label('dynamic_strtab', @tag['STRTAB']) @tag['STRTAB'] = l strtab = @encoded[l, sz].data end end end @tag.keys.each { |k| case k ...
interprets tags (convert flags, arrays etc), mark them as self.encoded.export
decode_segments_tags_interpret
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_symbol_export(s) if s.name and s.shndx != 'UNDEF' and %w[NOTYPE OBJECT FUNC].include?(s.type) if @header.type == 'REL' sec = @sections[s.shndx] o = sec.offset + s.value elsif not o = addr_to_off(s.value) # allow to point to end of segment if not seg = @segments.find { |seg_| seg_.type...
marks a symbol as @encoded.export (from s.value, using segments or sections)
decode_symbol_export
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_symbols return unless @tag['STRTAB'] and @tag['STRSZ'] and @tag['SYMTAB'] and (@tag['HASH'] or @tag['GNU_HASH']) raise "E: ELF: unsupported symbol entry size: #{@tag['SYMENT']}" if @tag['SYMENT'] != Symbol.size(self) # find number of symbols if @tag['HASH'] @encoded.ptr = @tag['HASH'] #...
read symbol table, and mark all symbols found as exports of self.encoded tables locations are found in self.tags XXX symbol count is found from the hash table, this may not work with GNU_HASH only binaries
decode_segments_symbols
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_relocs @relocations.clear if @encoded.ptr = @tag['REL'] raise "E: ELF: unsupported rel entry size #{@tag['RELENT']}" if @tag['RELENT'] != Relocation.size(self) p_end = @encoded.ptr + @tag['RELSZ'] while @encoded.ptr < p_end @relocations << Relocation.decode(self) end end if ...
decode relocation tables (REL, RELA, JMPREL) from @tags
decode_segments_relocs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_relocs_interpret relocproc = "arch_decode_segments_reloc_#{@header.machine.to_s.downcase}" if not respond_to? relocproc puts "W: Elf: relocs for arch #{@header.machine} unsupported" if $VERBOSE return end @relocations.each { |r| next if r.offset == 0 if not o = addr_to_off(r.offs...
use relocations as self.encoded.reloc
decode_segments_relocs_interpret
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def reloc_target(reloc) target = 0 if reloc.symbol.kind_of?(Symbol) if reloc.symbol.type == 'SECTION' s = @sections[reloc.symbol.shndx] if not target = @encoded.inv_export[s.offset] target = new_label(s.name) @encoded.add_export(target, s.offset) end elsif reloc.symbol.name target = ...
returns the target of a relocation using reloc.symbol may create new labels if the relocation targets a section
reloc_target
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def arch_decode_segments_reloc_386(reloc) if reloc.symbol.kind_of?(Symbol) and n = reloc.symbol.name and reloc.symbol.shndx == 'UNDEF' and @sections and s = @sections.find { |s_| s_.name and s_.offset <= @encoded.ptr and s_.offset + s_.size > @encoded.ptr } @encoded.add_export(new_label("#{s.name}_#{n}"), @enco...
returns the Metasm::Relocation that should be applied for reloc self.encoded.ptr must point to the location that will be relocated (for implicit addends)
arch_decode_segments_reloc_386
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def arch_decode_segments_reloc_mips(reloc) if reloc.symbol.kind_of?(Symbol) and n = reloc.symbol.name and reloc.symbol.shndx == 'UNDEF' and @sections and s = @sections.find { |s_| s_.name and s_.offset <= @encoded.ptr and s_.offset + s_.size > @encoded.ptr } @encoded.add_export(new_label("#{s.name}_#{n}"), @enc...
returns the Metasm::Relocation that should be applied for reloc self.encoded.ptr must point to the location that will be relocated (for implicit addends)
arch_decode_segments_reloc_mips
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def arch_decode_segments_reloc_x86_64(reloc) if reloc.symbol.kind_of?(Symbol) and n = reloc.symbol.name and reloc.symbol.shndx == 'UNDEF' and @sections and s = @sections.find { |s_| s_.name and s_.offset <= @encoded.ptr and s_.offset + s_.size > @encoded.ptr } @encoded.add_export(new_label("#{s.name}_#{n}"), @e...
returns the Metasm::Relocation that should be applied for reloc self.encoded.ptr must point to the location that will be relocated (for implicit addends)
arch_decode_segments_reloc_x86_64
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_leb(ed = @encoded) v = s = 0 loop { b = ed.read(1).unpack('C').first.to_i v |= (b & 0x7f) << s s += 7 break v if (b&0x80) == 0 } end
decode an ULEB128 (dwarf2): read bytes while high bit is set, littleendian
decode_leb
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_debug return if not @sections # assert presence of DWARF sections info = @sections.find { |sec| sec.name == '.debug_info' } abbrev = @sections.find { |sec| sec.name == '.debug_abbrev' } str = @sections.find { |sec| sec.name == '.debug_str' } return if not info or not abbrev # section -> conte...
decodes the debugging information if available only a subset of DWARF2/3 is handled right now most info taken from http://ratonland.org/?entry=39 & libdwarf/dwarf.h
decode_debug
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_dynamic(decode_relocs=true) return if not dynamic = @segments.find { |s| s.type == 'DYNAMIC' } @encoded.ptr = add_label('dynamic_tags', dynamic.vaddr) decode_tags decode_segments_tags_interpret decode_segments_symbols return if not decode_relocs decode_segments_relocs decode_segments...
decodes the ELF dynamic tags, interpret them, and decodes symbols and relocs
decode_segments_dynamic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments decode_segments_dynamic decode_sections_symbols #decode_debug # too many info, decode on demand @segments.each { |s| case s.type when 'LOAD', 'INTERP' sz = s.filesz pagepad = (-(s.offset + sz)) % 4096 s.encoded = @encoded[s.offset, sz] || EncodedData.new if s.type == 'L...
decodes the dynamic segment, fills segments.encoded
decode_segments
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_sections @symbols.clear # the NULL symbol is explicit in the symbol table decode_sections_symbols decode_sections_relocs @sections.each { |s| case s.type when 'PROGBITS', 'NOBITS' when 'TODO' # TODO end } @sections.find_all { |s| s.type == 'PROGBITS' or s.type == 'NOBITS' }.each { |s|...
decodes sections, interprets symbols/relocs, fills sections.encoded
decode_sections
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode decode_header case @header.type when 'DYN', 'EXEC'; decode_segments when 'REL'; decode_sections when 'CORE' end end
decodes the elf header, and depending on the elf type, decode segments or sections
decode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def cpu_from_headers case @header.machine when 'X86_64'; X86_64.new when '386'; Ia32.new when 'MIPS'; (@header.flags.include?('32BITMODE') ? MIPS64 : MIPS).new @endianness when 'PPC'; PPC.new when 'ARM'; ARM.new when 'SH'; Sh4.new else raise "unsupported cpu #{@header.machine}" end end
returns a metasm CPU object corresponding to +header.machine+
cpu_from_headers
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def get_default_entrypoints ep = [] ep << @header.entry if @header.entry != 0 @symbols.each { |s| ep << s.value if s.shndx != 'UNDEF' and s.type == 'FUNC' } if @symbols ep end
returns an array including the ELF entrypoint (if not null) and the FUNC symbols addresses TODO include init/init_array
get_default_entrypoints
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def init_disassembler d = super() d.backtrace_maxblocks_data = 4 if d.get_section_at(0) # fixes call [constructor] => 0 d.decoded[0] = true d.function[0] = @cpu.disassembler_default_func end case @cpu.shortname when 'ia32', 'x64' old_cp = d.c_parser d.c_parser = nil d.parse_c <<EOC void *d...
returns a disassembler with a special decodedfunction for dlsym, __libc_start_main, and a default function (i386 only)
init_disassembler
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def section_info if @sections @sections[1..-1].map { |s| [s.name, s.addr, s.size, s.flags.join(',')] } else @segments.map { |s| [nil, s.vaddr, s.memsz, s.flags.join(',')] } end end
returns an array of [name, addr, length, info]
section_info
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments if @load_address == 0 and @segments.find { |s| s.type == 'LOAD' and s.vaddr > @encoded.length } @load_address = @segments.find_all { |s| s.type == 'LOAD' }.map { |s| s.vaddr }.min end decode_segments_dynamic @segments.each { |s| if s.type == 'LOAD' s.encoded = @encoded[addr_to_off(...
decodes the dynamic segment, fills segments.encoded
decode_segments
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_header(off = 0) @encoded.ptr = off @header.decode self decode_program_header(@header.phoff+off) end
do not try to decode the section header by default
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def make_name_p elf return 0 if not name or @name == '' or elf.header.shnum == 0 if elf.header.shstrndx.to_i == 0 or not elf.sections[elf.header.shstrndx] sn = Section.new sn.name = '.shstrtab' sn.type = 'STRTAB' sn.flags = [] sn.addralign = 1 sn.encoded = EncodedData.new << 0 elf.head...
defines the @name_p field from @name and elf.section[elf.header.shstrndx] creates .shstrtab if needed
make_name_p
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def make_name_p(elf, strtab) s = strtab.kind_of?(EncodedData) ? strtab.data : strtab return if name_p and s[@name_p, @name.length+1] == @name+0.chr return if @name_p = s.index(@name+0.chr) @name_p = strtab.length strtab << @name << 0 end
sets the value of @name_p, appends @name to strtab if needed
make_name_p
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_check_section_size(s) if s.size and s.encoded.virtsize < s.size puts "W: Elf: preexisting section #{s} has grown, relocating" if $VERBOSE s.addr = s.offset = nil s.size = s.encoded.virtsize end end
checks a section's data has not grown beyond s.size, if so undefs addr/offset
encode_check_section_size
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_reorder_symbols gnu_hash_bucket_length = 42 # TODO @symbols[1..-1] = @symbols[1..-1].sort_by { |s| if s.bind != 'GLOBAL' -2 elsif s.shndx == 'UNDEF' or not s.name -1 else ELF.gnu_hash_symbol_name(s.name) % gnu_hash_bucket_length end } end
reorders self.symbols according to their gnu_hash
encode_reorder_symbols
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_add_section s # order: r rx rw noalloc rank = lambda { |sec| f = sec.flags sec.type == 'NULL' ? -2 : sec.addr ? -1 : f.include?('ALLOC') ? !f.include?('WRITE') ? !f.include?('EXECINSTR') ? 0 : 1 : 2 : 3 } srank = rank[s] nexts = @sections.find { |sec| rank[sec] > srank } # find section wit...
sorted insert of a new section to self.sections according to its permission (for segment merging)
encode_add_section
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_hash return if @symbols.length <= 1 if not hash = @sections.find { |s| s.type == 'HASH' } hash = Section.new hash.name = '.hash' hash.type = 'HASH' hash.flags = ['ALLOC'] hash.entsize = hash.addralign = 4 encode_add_section hash end hash.encoded = EncodedData.new # to find a sym...
encodes the symbol dynamic hash table in the .hash section, updates the HASH tag
encode_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_segments_symbols(strtab) return if @symbols.length <= 1 if not dynsym = @sections.find { |s| s.type == 'DYNSYM' } dynsym = Section.new dynsym.name = '.dynsym' dynsym.type = 'DYNSYM' dynsym.entsize = Symbol.size(self) dynsym.addralign = 4 dynsym.flags = ['ALLOC'] dynsym.info = @symbo...
encodes the symbol table should have a stable self.sections array (only append allowed after this step)
encode_segments_symbols
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_segments_relocs return if not @relocations or @relocations.empty? arch_preencode_reloc_func = "arch_#{@header.machine.downcase}_preencode_reloc" send arch_preencode_reloc_func if respond_to? arch_preencode_reloc_func list = @relocations.find_all { |r| r.type == 'JMP_SLOT' } if not list.empty? or ...
encodes the relocation tables needs a complete self.symbols array
encode_segments_relocs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def arch_386_preencode_reloc return if @relocations.empty? # if .got.plt does not exist, the dynamic loader segfaults if not gotplt = @sections.find { |s| s.type == 'PROGBITS' and s.name == '.got.plt' } gotplt = Section.new gotplt.name = '.got.plt' gotplt.type = 'PROGBITS' gotplt.flags = %w[ALLOC WRI...
creates the .plt/.got from the @relocations
arch_386_preencode_reloc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_segments_dynamic if not strtab = @sections.find { |s| s.type == 'STRTAB' and s.flags.include? 'ALLOC' } strtab = Section.new strtab.name = '.dynstr' strtab.addralign = 1 strtab.type = 'STRTAB' strtab.flags = ['ALLOC'] encode_add_section strtab end strtab.encoded = EncodedData.new << 0...
encodes the .dynamic section, creates .hash/.gnu.hash/.rel/.rela/.dynsym/.strtab/.init,*_array as needed
encode_segments_dynamic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def automagic_symbols GNUExports rescue return # autorequire autoexports = GNUExports::EXPORT.dup @sections.each { |s| next if not s.encoded s.encoded.export.keys.each { |e| autoexports.delete e } } @sections.each { |s| next if not s.encoded s.encoded.reloc.each_value { |r| et = r.target.exter...
creates the undef symbol list from the section.encoded.reloc and a list of known exported symbols (e.g. from libc) also populates @tag['NEEDED']
automagic_symbols
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def create_relocations @relocations = [] arch_create_reloc_func = "arch_#{@header.machine.downcase}_create_reloc" if not respond_to? arch_create_reloc_func puts "Elf: create_reloc: unhandled architecture #{@header.machine}" if $VERBOSE return end # create a fake binding with all our own symbols # no...
reads the existing segment/sections.encoded and populate @relocations from the encoded.reloc hash
create_relocations
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def arch_386_create_reloc(section, off, binding, rel=nil) rel ||= section.encoded.reloc[off] if rel.endianness != @endianness or not [:u32, :i32, :a32].include? rel.type puts "ELF: 386_create_reloc: ignoring reloc #{rel.target} in #{section.name}: bad reloc type" if $VERBOSE return end startaddr = label_a...
references to FUNC symbols are transformed to JMPSLOT relocations (aka call to .plt) TODO ET_REL support
arch_386_create_reloc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def invalidate_header @header.shoff = @header.shnum = nil @header.phoff = @header.phnum = nil @header.shstrndx = nil @sections.to_a.each { |s| s.name_p = nil s.offset = nil } @segments.to_a.each { |s| s.offset = nil } self end
resets the fields of the elf headers that should be recalculated, eg phdr offset
invalidate_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode_make_segments_from_sections # fixed addresses first seclist = @sections.find_all { |sec| sec.addr.kind_of? Integer }.sort_by { |sec| sec.addr } | @sections seclist.each { |sec| next if not sec.flags.to_a.include? 'ALLOC' # check if we fit in an existing segment loadsegs = @segments.find_all {...
put every ALLOC section in a segment, create segments if needed sections with a good offset within a segment are ignored
encode_make_segments_from_sections
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def encode(type='DYN') @header.type ||= {:bin => 'EXEC', :lib => 'DYN', :obj => 'REL'}.fetch(type, type) @header.machine ||= case @cpu.shortname when 'x64'; 'X86_64' when 'ia32'; '386' when 'mips'; 'MIPS' when 'powerpc'; 'PPC' when 'arm'; 'ARM' end if @header.type == 'REL' encode_rel ...
create the relocations from the sections.encoded.reloc create the dynamic sections put sections/phdr in PT_LOAD segments link TODO support mapped PHDR, obey section-specified base address, handle NOBITS encode ET_REL
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def parse_parser_instruction(instr) readstr = lambda { @lexer.skip_space t = nil raise instr, "string expected, found #{t.raw.inspect if t}" if not t = @lexer.readtok or (t.type != :string and t.type != :quoted) t.value || t.raw } check_eol = lambda { @lexer.skip_space t = nil raise instr, "e...
handles elf meta-instructions syntax: .section "<name>" [<perms>] [base=<base>] change current section (where normal instruction/data are put) perms = list of 'w' 'x' 'alloc', may be prefixed by 'no' 'r' ignored defaults to 'alloc' shortcuts: .text .data .rodata .bss base: immediate expression representing the section...
parse_parser_instruction
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def assemble(*a) parse(*a) if not a.empty? @source.each { |k, v| raise "no section named #{k} ?" if not s = @sections.find { |s_| s_.name == k } s.encoded << assemble_sequence(v, @cpu) v.clear } end
assembles the hash self.source to a section array
assemble
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def read_c_attrs(cp) cp.toplevel.symbol.each_value { |v| next if not v.kind_of? C::Variable if v.has_attribute 'export' or ea = v.has_attribute_var('export_as') s = Symbol.new s.name = ea || v.name s.type = v.type.kind_of?(C::Function) ? 'FUNC' : 'NOTYPE' s.bind = 'GLOBAL' s.shndx = 1 s....
handles C attributes: export, export_as(foo), import, import_from(libc.so.6), init, fini, entrypoint
read_c_attrs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_encode.rb
BSD-3-Clause
def decode_header @header.decode self @header.ncmds.times { @commands << LoadCommand.decode(self) } @commands.each { |cmd| e = cmd.data case cmd.cmd when 'SEGMENT', 'SEGMENT_64'; @segments << e end } end
decodes the Mach header from the current offset in self.encoded
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/macho.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/macho.rb
BSD-3-Clause
def segment_at(addr) return if not addr or addr <= 0 if seg = @segments.find { |seg_| addr >= seg_.virtaddr and addr < seg_.virtaddr + seg_.virtsize } seg.encoded.ptr = addr - seg.virtaddr seg end end
return the segment containing address, set seg.encoded.ptr to the correct offset
segment_at
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/macho.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/macho.rb
BSD-3-Clause
def parse_parser_instruction(instr) readstr = lambda { @lexer.skip_space t = nil raise instr, "string expected, found #{t.raw.inspect if t}" if not t = @lexer.readtok or (t.type != :string and t.type != :quoted) t.value || t.raw } check_eol = lambda { @lexer.skip_space t = nil raise instr, "e...
handles macho meta-instructions syntax: .section "<name>" [<perms>] change current section (where normal instruction/data are put) perms = list of 'r' 'w' 'x', may be prefixed by 'no' shortcuts: .text .data .rodata .bss .entrypoint [<label>] defines the program entrypoint to the specified label / current location
parse_parser_instruction
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/macho.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/macho.rb
BSD-3-Clause
def assemble(*a) parse(*a) if not a.empty? @source.each { |k, v| raise "no segment named #{k} ?" if not s = @segments.find { |s_| s_.name == k } s.encoded << assemble_sequence(v, @cpu) v.clear } end
assembles the hash self.source to a section array
assemble
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/macho.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/macho.rb
BSD-3-Clause
def compile_c(source, file='<unk>', lineno=1) cp = @cpu.new_cparser tune_cparser(cp) cp.parse(source, file, lineno) read_c_attrs cp if respond_to? :read_c_attrs asm_source = @cpu.new_ccompiler(cp, self).compile puts asm_source if $DEBUG assemble(asm_source, 'C compiler output', 1) c_set_default_entrypoi...
parses a bunch of standalone C code, compile and assemble it
compile_c
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def compile_setsection(src, section) src << section end
add directive to change the current assembler section to the assembler source +src+
compile_setsection
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def init_disassembler @disassembler ||= Disassembler.new(self) @disassembler.cpu ||= cpu each_section { |edata, base| edata ||= EncodedData.new @disassembler.add_section edata, base } @disassembler end
returns the exe disassembler if it does not exist, creates one, and feeds it with the exe sections
init_disassembler
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def disassemble(*entrypoints) entrypoints = get_default_entrypoints if entrypoints.empty? disassembler.disassemble(*entrypoints) @disassembler end
disassembles the specified entrypoints initializes the disassembler if needed uses get_default_entrypoints if the argument list is empty returns the disassembler
disassemble
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def disassemble_fast_deep(*entrypoints) entrypoints = get_default_entrypoints if entrypoints.empty? disassembler.disassemble_fast_deep(*entrypoints) @disassembler end
disassembles the specified entrypoints without backtracking initializes the disassembler if needed uses get_default_entrypoints if the argument list is empty returns the disassembler
disassemble_fast_deep
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def encode_string(*a) encode(*a) raise ["Unresolved relocations:", @encoded.reloc.map { |o, r| "#{r.target} " + (Backtrace.backtrace_str(r.backtrace) if r.backtrace).to_s }].join("\n") if not @encoded.reloc.empty? @encoded.data end
encodes the executable as a string, checks that all relocations are resolved, and returns the raw string version
encode_string
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def encode_file(path, *a) encode_string(*a) File.open(path, 'wb') { |fd| fd.write(@encoded.data) } end
saves the result of +encode_string+ in the specified file overwrites existing files
encode_file
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def int_from_hash(val, hash) val.kind_of?(Integer) ? hash.index(val) || val : hash.index(val) or raise "unknown constant #{val.inspect}" end
converts a constant name to its numeric value using the hash {1 => 'toto', 2 => 'tata'}: 'toto' => 1, 42 => 42, 'tutu' => raise
int_from_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def bits_from_hash(val, hash) val.kind_of?(Array) ? val.inject(0) { |val_, bitname| val_ | int_from_hash(bitname, hash) } : int_from_hash(val, hash) end
converts an array of flag constants to its numeric value using the hash {1 => 'toto', 2 => 'tata'}: ['toto', 'tata'] => 3, 'toto' => 2, 42 => 42
bits_from_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def int_to_hash(val, hash) val.kind_of?(Integer) ? hash.fetch(val, val) : (hash.index(val) ? val : raise("unknown constant #{val.inspect}")) end
converts a numeric value to the corresponding constant name using the hash {1 => 'toto', 2 => 'tata'}: 1 => 'toto', 42 => 42, 'tata' => 'tata', 'tutu' => raise
int_to_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def bits_to_hash(val, hash) (val.kind_of?(Integer) ? (hash.find_all { |k, v| val & k == k and val &= ~k }.map { |k, v| v } << val) : val.kind_of?(Array) ? val.map { |e| int_to_hash(e, hash) } : [int_to_hash(val, hash)]) - [0] end
converts a numeric value to the corresponding array of constant flag names using the hash {1 => 'toto', 2 => 'tata'}: 5 => ['toto', 4]
bits_to_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/main.rb
BSD-3-Clause
def assemble(*a) parse(*a) if not a.empty? @body << assemble_sequence(@source, @cpu) @body.fixup @body.binding # XXX should create @relocs here @source.clear end
assembles the source in the body, clears the source
assemble
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def pre_encode relocs = @relocs.inject(EncodedData.new) { |edata, r| edata << r.encode(self) } header = @header.encode self, relocs [header, relocs, @body] end
encodes the header and the relocation table, return them in an array, with the body.
pre_encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def parse_parser_instruction(instr) case instr.raw.downcase when '.entrypoint' # ".entrypoint <somelabel/expression>" or ".entrypoint" (here) @lexer.skip_space if tok = @lexer.nexttok and tok.type == :string raise instr, 'syntax error' if not entrypoint = Expression.parse(@lexer) else entrypoint...
defines the exe-specific parser instructions: .entrypoint [<label>]: defines the program entrypoint to label (or create a new label at this location)
parse_parser_instruction
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def encode pre_encode.inject(@encoded) { |edata, pe| edata << pe } @encoded.fixup @encoded.binding encode_fix_checksum end
concats the header, relocation table and body
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def decode_header @header.decode self end
decodes the MZ header from the current offset in self.encoded
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def decode_body @body = @encoded[@header.cparhdr*16...@header.cp*512+@header.cblp] @body.virtsize += @header.minalloc * 16 @body.add_export 'start', @header.cs * 16 + @header.ip end
decodes the main part of the program mostly defines the 'start' export, to point to the MZ entrypoint
decode_body
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/mz.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/mz.rb
BSD-3-Clause
def decode_header @header = Header.decode(self) end
decodes the header from the current offset in self.encoded
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/nds.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/nds.rb
BSD-3-Clause
def decode_header @cursection ||= self @encoded.ptr = 0x3c @encoded.ptr = decode_word(@encoded) @signature = @encoded.read(4) raise InvalidExeFormat, "Invalid PE signature #{@signature.inspect}" if @signature != MAGIC @coff_offset = @encoded.ptr if @mz.encoded.empty? @mz.encoded << @encoded[0, @coff_of...
overrides COFF#decode_header simply sets the offset to the PE pointer before decoding the COFF header also checks the PE signature
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def encode_default_mz_header # XXX use single-quoted source, to avoid ruby interpretation of \r\n @mz.cpu = Ia32.new(386, 16) @mz.assemble <<'EOMZSTUB' db "Needs Win32!\r\n$" .entrypoint push cs pop ds xor dx, dx ; ds:dx = addr of $-terminated string mov ah, 9 ; output string int 21h mov ax, ...
creates a default MZ file to be used in the PE header this one is specially crafted to fit in the 0x3c bytes before the signature
encode_default_mz_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def encode_header(*a) encode_default_mz_header if @mz.encoded.empty? @encoded << @mz.encoded.dup # append the PE signature @signature ||= MAGIC @encoded << @signature super(*a) end
encodes the PE header before the COFF header, uses a default mz header if none defined the MZ header must have 0x3c pointing just past its last byte which should be 8bytes aligned the 2 1st bytes of the MZ header should be 'MZ'
encode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def mini_copy(share_ns=true) ret = self.class.new(@cpu) ret.share_namespace(self) if share_ns ret.header.machine = @header.machine ret.header.characteristics = @header.characteristics ret.optheader.entrypoint = @optheader.entrypoint ret.optheader.image_base = @optheader.image_base ret.optheader.subsystem ...
a returns a new PE with only minimal information copied: section name/perm/addr/content exports imports (with boundimport cleared) resources
mini_copy
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def get_xrefs_x(dasm, di) if @cpu.shortname =~ /^ia32|^x64/ and a = di.instruction.args.first and a.kind_of?(Ia32::ModRM) and a.seg and a.seg.val == 4 and w = get_xrefs_rw(dasm, di).find { |type, ptr, len| type == :w and ptr.externals.include? 'segment_base_fs' } and dasm.backtrace(Expression[w[1], :-, 'segme...
handles writes to fs:[0] -> dasm SEH handler (first only, does not follow the chain) TODO seh prototype (args => context) TODO hook on (non)resolution of :w xref
get_xrefs_x
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def init_disassembler d = super() d.backtrace_maxblocks_data = 4 case @cpu.shortname when 'ia32', 'x64' old_cp = d.c_parser d.c_parser = nil d.parse_c '__stdcall void *GetProcAddress(int, char *);' d.parse_c '__stdcall void ExitProcess(int) __attribute__((noreturn));' d.c_parser.lexer.define_weak...
returns a disassembler with a special decodedfunction for GetProcAddress (i386 only), and the default func
init_disassembler
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def decode_section_body(s) s.encoded = @encoded[s.virtaddr, s.virtsize] || EncodedData.new end
use the virtualaddr/virtualsize fields of the section header
decode_section_body
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def memdump_imports(memory, dump, unk_iat_p=nil) puts 'rebuilding imports...' if $VERBOSE if unk_iat_p # read iat data from unk_iat_p iat_p = unk_iat_p else return if not imports # read iat data from @imports imports = @imports.dup imports.each { |id| id.iat = id.iat.dup } iat_p = imports.fir...
rebuilds an IAT from the loaded pe and the memory for each loaded iat, find the matching dll in memory for each loaded iat entry, retrieve the exported name from the loaded dll OR from a base iat address in memory (unk_iat_p, rva), retrieve the 1st dll, find all iat pointers/forwarders to this dll, on failure try to fi...
memdump_imports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pe.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pe.rb
BSD-3-Clause
def code_at_off(off) @all_code.find { |c| c[:fileoff] <= off and c[:fileoff] + c[:code].length > off } end
return the :code part which contains off
code_at_off
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/pyc.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/pyc.rb
BSD-3-Clause
def new_field(name, decode, encode, defval, enum=nil, bits=nil) if name attr_accessor name name = "@#{name}".to_sym end (@@fields[self] ||= []) << [name, decode, encode, defval, enum, bits] end
defines a new field adds an accessor
new_field
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/serialstruct.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb
BSD-3-Clause
def new_int_field(*types) recv = class << self ; self ; end types.each { |type| recv.send(:define_method, type) { |name, *args| new_field(name, "decode_#{type}".to_sym, "encode_#{type}".to_sym, args[0] || 0, args[1]) } # shortcut to define multiple fields of this type with default values recv.send(...
creates a field constructor for a simple integer relies on exe implementing (en,de)code_#{type}
new_int_field
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/serialstruct.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb
BSD-3-Clause
def virtual(*a) a.each { |f| new_field(f, nil, nil, nil) } end
standard fields: virtual field, handled explicitly in a custom encode/decode
virtual
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/serialstruct.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb
BSD-3-Clause
def bitfield(inttype, h) # XXX encode/decode very not threadsafe ! this is a Georges Foreman Guarantee. # could use a me.instance_variable.. # decode the value in a temp var d = lambda { |exe, me| @bitfield_val = exe.send("decode_#{inttype}") } # reset a temp var e = lambda { |exe, me, val| @bitfield_val =...
define a bitfield: many fields inside a single word/byte/whatever usage: bitfield :word, 0 => :lala, 1 => nil, 4 => :lolo, 8 => :foo => a bitfield read using exe.decode_word, containing 3 subfields: :lala (bits 0...1), (discard 3 bits), :lolo (bits 4...8), and :foo (bits 8..-1) fields default to 0
bitfield
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/serialstruct.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb
BSD-3-Clause
def decode_hook(before=nil, &b) @@fields[self] ||= [] idx = (before ? @@fields[self].index(fld_get(before)) : -1) @@fields[self].insert(idx, [nil, b]) end
inject a hook to be run during the decoding process
decode_hook
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/serialstruct.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb
BSD-3-Clause