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 Linux/sparc the following code will emit three magic letters instead of just dumping core.

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

Command: pre/sparc-debian2.2-linux/magic_elf/cc.sh
/usr/bin/gcc \
	-Wall -O1 -I . -I out/sparc-debian2.2-linux -D NDEBUG \
	-o tmp/sparc-debian2.2-linux/magic_elf/magic_elf \
	pre/sparc-debian2.2-linux/magic_elf/magic_elf.c \
&& tmp/sparc-debian2.2-linux/magic_elf/magic_elf

Output: out/sparc-debian2.2-linux/magic_elf/magic_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-debian2.2-linux/magic_elf/xxd.sh
/usr/bin/xxd -l 80 \
< tmp/sparc-debian2.2-linux/magic_elf/magic_elf

Output: out/sparc-debian2.2-linux/magic_elf/xxd
0000000: 7f45 4c46 0102 0100 0000 0000 0000 0000  .ELF............
0000010: 0002 0002 0000 0001 0001 0630 0000 0034  ...........0...4
0000020: 0000 1c94 0000 0000 0034 0020 0006 0028  .........4. ...(
0000030: 001b 0018 0000 0006 0000 0034 0001 0034  ...........4...4
0000040: 0001 0034 0000 00c0 0000 00c0 0000 0005  ...4............

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 0x1073c is a plausible address of function main.

2.4. Other roads to ELF

The classic tool for conversion from hex to decimal is bc, a front end to dc. dc itself lacks standardized commands for nice output. Command n is a rather recent GNU extension and not available on bc-1.04-39 shipped with SuSE Linux 6.0.



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