Last active
January 10, 2022 00:29
-
-
Save bluec0re/f7c7f0e696159397e4dc to your computer and use it in GitHub Desktop.
Tunnels every python code through HTTP proxies by patching socket.socket. Just import the module.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import socket | |
import os | |
# backup original function | |
_socket = socket.socket | |
class SocketProxyWrapper: | |
def __init__(self, socket, proxy): | |
self.proxy = proxy | |
self.socket = socket | |
def connect(self, addr): | |
# do HTTP connect | |
self.socket.connect(self.proxy) | |
self.socket.sendall("CONNECT {0}:{1} HTTP/1.1\r\nHost: {0}:{1}\r\nProxy-Connection: keep-alive\r\n\r\n".format(*addr)) | |
# fetch response | |
data = '' | |
while not data.endswith('\r\n\r\n'): | |
c = self.socket.recv(1) | |
if not c: | |
break | |
data += c | |
def __getattr__(self, name): | |
# pass everything to socket object | |
return getattr(self.socket, name) | |
def socket_wrapper(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0): | |
# tunnel only TCP | |
if family in (socket.AF_INET, socket.AF_INET6) and type == socket.SOCK_STREAM: | |
return SocketProxyWrapper(_socket(family, type, proto), proxy) | |
return _socket(family, type, proto) | |
if os.environ.get('HTTP_PROXY'): | |
socket.socket = socket_wrapper | |
# http://<ip>:<port>/ -> (<ip>, <port>) | |
proxy = os.environ.get('HTTP_PROXY').replace('http://', '').replace('/', '').split(':') | |
proxy[1] = int(proxy[1]) | |
proxy = tuple(proxy) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment