Skip to content

Instantly share code, notes, and snippets.

@dracos
Created Mar 16, 2017
Embed
What would you like to do?
A python proxy
import re
import socket
import signal
import sys
import threading
def sigint_received(signum, frame):
sys.exit(0)
signal.signal(signal.SIGINT, sigint_received)
PORT = 8080
regexHost = re.compile(r'Host: ([^\s]*)', re.IGNORECASE)
regexXFF = re.compile(r'X-Forwarded-For: ([^\s]*)', re.IGNORECASE)
regexUri = re.compile(r'((?:GET|POST) [^\s]*)')
class ConnectionThread(threading.Thread):
def __init__(self, (conn,addr)):
self.conn = conn
self.addr = addr
threading.Thread.__init__(self)
def run(self):
data = self.conn.recv(1024*1024)
try:
host = regexHost.search(data).groups()[0]
uri = regexUri.search(data).groups()[0]
xff = regexXFF.search(data).groups()[0]
print '%s, %s, %s' % (xff, host, uri)
except:
print 'None found, defaulting'
host = 'DEFAULT'
request = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#request.settimeout(6)
request.connect((host, 80))
request.send(data)
while 1:
temp = request.recv(1024)
if not temp: break
self.conn.send(temp)
self.conn.close()
class ProxyThread(threading.Thread):
def __init__(self, port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('0.0.0.0', port))
threading.Thread.__init__(self)
def run(self):
self.sock.listen(10)
while 1:
temp = ConnectionThread(self.sock.accept())
temp.daemon = True
temp.start()
if __name__ == "__main__":
proxy = ProxyThread(PORT)
proxy.daemon = True
proxy.start()
print "Started a proxy on port", PORT
while 1:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment