Thursday, September 13, 2012

relinking an elf executable

in the olden days on AIX you could easily relink an executable by simply relinking: gcc -o newbinary oldbinary newcode.o. this made it very easy to patch a binary without doing a full build.

for example. lets say we have the following program:

myprog.c:
#include <stdio.h>

void foo()
{
    printf("foo\n");
}

int main()
{
    foo();
}
so you compile: gcc -o myprog myprog.c. when you run it, you see:
breed@maluca:~$ ./myprog
foo
awesome right? well after a few days, you get bored of seeing "foo", and you would really like to see "goo" instead. but alas, you have lost the source for myprog.c. what can you do? will you never see myprog output goo?

never fear elfsh is here! it's a very cool, albeit abandoned, project. lets patch myprog:

first we want to write a new function:

goo.c:

void goo()
{
    printf("goo\n");
}

then we compile it: gcc -c goo.c

if only we could relink myprog... well we can get close with elfsh. check out the following:

(elfsh-0.82-b2-dev@local) load ./myprog
 [*] Thu Sep 13 00:52:44 2012 - New object loaded : ./myprog
(elfsh-0.82-b2-dev@local) load ./goo.o
 [*] Thu Sep 13 00:52:48 2012 - New object loaded : ./goo.o
(elfsh-0.82-b2-dev@local) reladd 1 2
 [E] Failed to inject ET_REL with workspace
(elfsh-0.82-b2-dev@local) reladd 1 2
 [*] ET_REL ./goo.o injected succesfully in ET_EXEC ./myprog
(elfsh-0.82-b2-dev@local) redir foo goo
Found sect .text at off 50132
 [*] Function foo redirected to addr 0x0804313F <goo>
(elfsh-0.82-b2-dev@local) save mynewprog
 [*] Object mynewprog saved successfully
(elfsh-0.82-b2-dev@local) quit

first we load the executable and the object file we want to link in. then we add them together. (for some reason you have to do it twice...) finally, you remap the symbol foo to goo.

now we run mynewprog:

breed@maluca:~$ ./mynewprog
goo

yay! we now we can bask in the glory of goo!

tragically it appears that the elfsh project may be abandoned, and 64-bit support seems to be lacking. perhaps someone will get excited about it and start enhancing it again...

2 comments:

  1. I've did it exactly the same, but when i try to run the generated executable, its just crashing with the message "Killed". Any clue what could be wrong?

    ReplyDelete
  2. I spend several hours compile it but freak out to find it doesn't work in x86-64

    Architecture EM_X86_64 : AMDx86-64 architecture not supported. No flowjack available.

    ReplyDelete