2. The magic of the Elf

 

Any sufficiently advanced technology is indistinguishable from magic.

 Arthur C. Clarke

For the first example I'll present the simplest piece of code that still gives sufficient feedback. Our aim is to implant it into /bin/sh. On practically every recent installation of SunOS/sparc the following code will emit three magic letters instead of just dumping core.

Source: pre/sparc-sunos5.7/magic_elf/magic_elf.c
#include <unistd.h>
int main() { write(1, (void*)0x10001, 3); return 0; }

Command: pre/sparc-sunos5.7/magic_elf/cc.sh
#!/usr/xpg4/bin/sh
/usr/local/bin/gcc -Wall -O1 -I . -I out/sparc-sunos5.7 -D NDEBUG \
	pre/sparc-sunos5.7/magic_elf/magic_elf.c \
	-o tmp/sparc-sunos5.7/magic_elf/magic_elf \
&& tmp/sparc-sunos5.7/magic_elf/magic_elf

Output: out/sparc-sunos5.7/magic_elf/magic_elf
ELF

2.1. How it works

2.2. Strings and dumps

What would you do if you knew nothing about ELF and just asked yourself how that example works? How can you go sure that the executable file really contains those three letters?

2.2.4. xxd

xxd is part of vim. [2] And though that can't be called installation core it comes pretty close on Linux distributions.

Anyway, at this point we can guess that file offset 1 and 0x10000 + 1 are not coincidental. A test program might help.

2.3. The address of main

Note that the output of %p is not standardized. Some platforms print a leading 0x, some don't. Even %#p does not guarantee a leading 0x. Anyway, output looks good. The byte at address 0x10000 + 0 is equal to that at file offset 0. And 0x10658 is a plausible address of function main.

2.4. Other roads to ELF

I found nothing equivalent to Linux's /proc/self/mem.

Notes

[1]

http://www.tuxedo.org/~esr/jargon/html/entry/RTFM.html

[2]

http://www.vim.org