cielseven's picture
add the experiment harnesses for t1 to t4 and t3-flat
28adce7
Raw History Blame Contribute Delete
5.35 kB
"""Minimal egress proxy: HTTP CONNECT to an allowlist of hosts, everything else refused and logged.
Runs as a sidecar attached to both the internal attempt network and the outside. Stdlib only.
Env: ALLOW = comma-separated host names (exact match, or a leading "." for a suffix match);
PORT = listen port (default 3128);
UPSTREAM = host:port of an HTTP CONNECT proxy to chain through (default: connect directly);
UPSTREAM_BYPASS = comma-separated hosts reached directly even when UPSTREAM is set.
Log lines (stdout): "<ts> ALLOW host:port [via upstream | direct (bypass)]" / "<ts> DENY host:port <reason>".
"""
import os
import select
import socket
import socketserver
import sys
import time
ALLOW = [h.strip().lower() for h in os.environ.get("ALLOW", "").split(",") if h.strip()]
PORT = int(os.environ.get("PORT", "3128"))
UPSTREAM = os.environ.get("UPSTREAM", "").strip()
UPSTREAM_BYPASS = [h.strip().lower() for h in os.environ.get("UPSTREAM_BYPASS", "").split(",") if h.strip()]
def upstream_for(host: str) -> str:
"""The CONNECT proxy to chain through for ``host``: none for a bypassed host."""
return "" if host.lower() in UPSTREAM_BYPASS else UPSTREAM
def allowed(host: str) -> bool:
host = host.lower()
for rule in ALLOW:
if rule.startswith("."):
if host == rule[1:] or host.endswith(rule):
return True
elif host == rule:
return True
return False
def connect(host: str, port: int, upstream: str = UPSTREAM) -> socket.socket:
"""A socket to host:port: direct, or a CONNECT tunnel through ``upstream`` ("host:port").
Raises OSError when the connection or the upstream's CONNECT fails."""
if not upstream:
return socket.create_connection((host, port), timeout=20)
up_host, _, up_port = upstream.rpartition(":")
sock = socket.create_connection((up_host, int(up_port)), timeout=20)
try:
sock.sendall(f"CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\n\r\n".encode("ascii"))
reply = b""
while not reply.endswith(b"\r\n\r\n"): # byte-wise: tunnel bytes may follow at once
byte = sock.recv(1)
if not byte:
raise OSError("upstream closed before answering CONNECT")
reply += byte
if len(reply) > 65536:
raise OSError("upstream CONNECT reply too long")
status = reply.split(b"\r\n", 1)[0].decode("latin-1", "replace")
parts = status.split()
if len(parts) < 2 or parts[1] != "200":
raise OSError(f"upstream refused CONNECT: {status.strip()}")
except Exception:
sock.close()
raise
sock.settimeout(None)
return sock
def log(kind: str, target: str, reason: str = "") -> None:
print(f"{time.strftime('%Y-%m-%dT%H:%M:%S')} {kind} {target} {reason}".rstrip(), flush=True)
class Handler(socketserver.StreamRequestHandler):
def handle(self) -> None:
line = self.rfile.readline(8192).decode("latin-1", "replace").strip()
parts = line.split()
# consume the rest of the request headers
while True:
header = self.rfile.readline(8192)
if not header or header in (b"\r\n", b"\n"):
break
if len(parts) != 3 or parts[0] != "CONNECT":
log("DENY", parts[1] if len(parts) > 1 else "?", "non-CONNECT request")
self.wfile.write(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n")
return
target = parts[1]
host, _, port = target.rpartition(":")
if not host or not port.isdigit() or int(port) != 443:
log("DENY", target, "not port 443")
self.wfile.write(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n")
return
if not allowed(host):
log("DENY", target, "not in allowlist")
self.wfile.write(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n")
return
try:
upstream = connect(host, int(port), upstream_for(host))
except OSError as error:
log("DENY", target, f"connect failed: {error}")
self.wfile.write(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n")
return
chain = upstream_for(host)
log("ALLOW", target, f"via {chain}" if chain else ("direct (bypass)" if UPSTREAM else ""))
self.wfile.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
client = self.connection
sockets = [client, upstream]
try:
while True:
readable, _, _ = select.select(sockets, [], [], 300)
if not readable:
break
for src in readable:
data = src.recv(65536)
if not data:
return
(upstream if src is client else client).sendall(data)
except OSError:
pass
finally:
upstream.close()
class Server(socketserver.ThreadingTCPServer):
allow_reuse_address = True
daemon_threads = True
if __name__ == "__main__":
print(f"egress proxy on :{PORT}, allow={ALLOW}, upstream={UPSTREAM or 'direct'}, bypass={UPSTREAM_BYPASS}",
file=sys.stderr, flush=True)
Server(("0.0.0.0", PORT), Handler).serve_forever()