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. [1] 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.9/magic_elf/magic_elf.c
#include <unistd.h>
int main() { write(1, (void*)0x10001, 3); return 0; }

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

Output: out/sparc-sunos5.9/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. [3] And though that can't be called installation core it comes pretty close on Linux distributions.

Source: pre/sparc-sunos5.9/magic_elf/xxd.sh
#!/usr/xpg4/bin/sh
/opt/sfw/bin/xxd -l 80 \
< tmp/sparc-sunos5.9/magic_elf/magic_elf

Output: out/sparc-sunos5.9/magic_elf/xxd
0000000: 7f45 4c46 0102 0100 0000 0000 0000 0000  .ELF............
0000010: 0002 0002 0000 0001 0001 042c 0000 0034  ...........,...4
0000020: 0000 13ec 0000 0000 0034 0020 0005 0028  .........4. ...(
0000030: 001b 0019 0000 0006 0000 0034 0001 0034  ...........4...4
0000040: 0000 0000 0000 00a0 0000 00a0 0000 0005  ................

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 0x105c0 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]

On this platform it's actually /usr/bin/csh. This is the result of a systematic search at A kingdom for a shell.

[2]

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

[3]

http://www.vim.org