Regular SOCKS4 Proxy

host = "127.0.0.1"
port = 3333

import socket
import struct
import threading

def TCPstreamReferrer(from_conn, to_conn):
    while True:
        try:
            data = from_conn.recv(4096)
            to_conn.sendall(data)
        except:
            from_conn.close()
            to_conn.close()

def CommandEstablishTCPstream(client, port, ip):
    proxy_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    proxy_conn.connect((ip, port))
    proxy_to_server = threading.Thread(target=TCPstreamReferrer, args=(client, proxy_conn,))
    proxy_to_client = threading.Thread(target=TCPstreamReferrer, args=(proxy_conn, client,))
    proxy_to_server.start()
    proxy_to_client.start()

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.settimeout(1)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((host, port))
server.listen(50)

while True:
    try:
        conn,addr=server.accept()
        print(addr[0]+":"+str(addr[1])+" connected.")
        try:
            data = conn.recv(512)
            print()
            version, command, port = struct.unpack("!BBH", data[0:4])
            ip                     = ".".join(str(octet) for octet in struct.unpack("!BBBB", data[4:8]))
            other = data[8:]
            if command == 0x01:
                conn.sendall(b"\x00\x5A\x00\x00\x00\x00\x00\x00")
                thread = threading.Thread(target=CommandEstablishTCPstream, args=(conn, port, ip,))
                print("Client "+addr[0]+":"+str(addr[1])+" established a connection to "+ip+":"+str(port))
                thread.start()
            elif command == 0x02:
                conn.sendall(b"\x00\x5B\x00\x00\x00\x00\x00\x00")
                print("Client "+addr[0]+":"+str(addr[1])+" tries to bind to "+ip+":"+str(port))
        except Exception as e:
            print(str(e))
            conn.close()
    except:
        pass
1 Like