6

I am in Linux, and I have seen this question a few times but never, nobody answered how to really make this work.

I need to add a section to an already compiled binary. Lets say for a moment is an ELF file. I'm using objcopy so this should be generic for any format because objcopy uses libbfd that handles many formats.

My process is as follows.

I create the bytecode for a section I want to append to an already compiled ELF file. Let's name this file bytecode.bin

Then I do:

objcopy --add-section .mysection=bytecode.bin \
--set-section-flags .mysection=code,contents,alloc,load,readonly \
myprogram myprogram_edited

Then I adjust the VMA of the secition:

objcopy --adjust-section-vma .mysection=$((16#XXXXX)) myprogram_edited myprogram_edited

Where XXXXXX is the new VMA address for the section.

I get the warning:

objcopy: stIbZt3t: warning: allocated section `.mysection' not in segment

When I do:

objdump -d myprogram_edited

I see:

Disassembly of section .mysection:

0000000000201011 <.mysection>:
...
...

So I see the section is created OK and the VMA adjusted. But the section is not mapped to segments, so it can't be loaded at runtime.

How can I solve this?

EDIT:

I opted for using Intel's PIN tool. Very useful and powerful for RI and binary injection.

0xfede7c8
  • 243
  • 2
  • 8

3 Answers3

6

libbfd is not a magic wand, it is in fact pretty limited (it's one of the reasons why GDB cannot debug files without a section table). In particular, objcopy won't add PHT entries for you, so you will have to extend or adjust the PHT manually. You can either do it manually with a hex editor or try using a library such as libelf (it gives you necessary primitives but you'll need to implement the logic yourself).

Igor Skochinsky
  • 36,553
  • 7
  • 65
  • 115
  • 1
    "it's one of the reasons why GDB cannot debug files without a section table" - thats something I've been wondering about for a while. Thanks for mentioning this – julian Mar 01 '17 at 09:57
  • The problem is, I need some generic tool that handles more executable file formats, not only ELF. But I think it is already a nice problem with ELF only. – 0xfede7c8 Mar 01 '17 at 18:44
  • Well, I'm not aware of any such tool so I guess you'll have to write your own. – Igor Skochinsky Mar 01 '17 at 19:31
1

Maybe you can look at LIEF:

GitHub page: https://github.com/lief-project/LIEF

Site: https://lief.quarkslab.com

x2d2
  • 21
  • 1
  • 5
    Your answer would be much more valuable if you can provide a basic example on how to code what is asked in LIEF. – perror Apr 05 '17 at 10:31
-1

I ended up using Intel PIN

Edit: I know this isn't actually an answer to the question. I was trying to change the behavior of a native executable and thought that I needed to change the binary on disk, when actually a binary instrumentation tool was enough for my purpuse.

0xfede7c8
  • 243
  • 2
  • 8