LIEF icon indicating copy to clipboard operation
LIEF copied to clipboard

ELF - Add call to libc function

Open dzonerzy opened this issue 5 years ago • 1 comments

Hi I have a simple program like this

int main() {
printf("Hello world");
return 0;
}

I need to add a call to libc function signal so i need to create a plt/got entry to resolve the address of signal at runtime, how this can by done with lief?

Thank you for your support.

dzonerzy avatar Jun 28 '19 11:06 dzonerzy

I'm not sure how to utilize PLT/GOT, but you can just add your own jumptable in new segment:

import lief
import struct

binary = lief.parse('a.out')

# add new segment with jumptable
jumptable = lief.ELF.Segment()
jumptable.type = lief.ELF.SEGMENT_TYPES.LOAD
jumptable.add(lief.ELF.SEGMENT_FLAGS.R)
jumptable.add(lief.ELF.SEGMENT_FLAGS.W)
jumptable.content = [0] * 0x1000
reloc_addr = binary.add(jumptable).virtual_address

# add relocation into our jumptable
symbol = lief.ELF.Symbol()
symbol.name = 'signal'
symbol.size = 0
symbol.value = 0
symbol.binding = lief.ELF.SYMBOL_BINDINGS.GLOBAL

relocation = lief.ELF.Relocation(reloc_addr, type=lief.ELF.RELOCATION_X86_64.GLOB_DAT, is_rela=True)
relocation.addend = 0
relocation.symbol = symbol

binary.add_dynamic_relocation(relocation)

callsite_addr = # virtual address where to inject CALL [rel reloc_addr] instruction
binary.patch_address(callsite_addr, [0xff, 0x15] + list(struct.pack('<i', reloc_addr - callsite_addr - 6)))
# (only for example, of course it also needs argument setup to work)

reloc_addr += 8 # more relocations could be added after that

binary.write('patched')

Milek7 avatar May 08 '21 20:05 Milek7