Files
coarena-autoreg/proxy_multi.py
T

177 lines
5.8 KiB
Python

"""Authenticated HTTP CONNECT proxy that pins each connection to a chosen source IP.
One port exposes N egress IPs: `user-N` in the proxy login always dials the N-th
address from --ips (sticky), a login without the suffix round-robins. All listed
addresses must already be configured on the interface (`ip -4 addr show`).
python3 proxy_multi.py --port 8888 --user mr --pass secret \
--ips 203.0.113.10,203.0.113.11,198.51.100.7
curl -x http://mr-1:secret@host:8888 https://api.ipify.org # always .11
Run detached so an ssh session cannot take it down:
setsid nohup python3 proxy_multi.py ... > /root/proxy_multi.log 2>&1 < /dev/null &
Stop by explicit PID (pkill -f trips interpreter-name guards):
PID=$(ss -lntp | sed -n 's/.*pid=\\([0-9]*\\).*/\\1/p' | head -1); kill $PID
Playwright needs credentials as fields, not in the URL:
proxy={"server": "http://host:8888", "username": "mr-1", "password": "secret"}
`requests` accepts them inside the proxy URL.
"""
import argparse
import asyncio
import base64
import itertools
import sys
IPS = []
CYCLE = None
USER = ""
PASS = ""
FAILS = {}
async def pipe(reader, writer):
try:
while True:
data = await reader.read(65536)
if not data:
break
writer.write(data)
await writer.drain()
except Exception:
pass
finally:
try:
writer.close()
except Exception:
pass
async def handle(reader, writer):
try:
head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=20)
except Exception:
writer.close()
return
lines = head.decode("latin-1").split("\r\n")
parts = lines[0].split()
if len(parts) < 3:
writer.write(b"HTTP/1.1 400 Bad Request\r\n\r\n")
writer.close()
return
method, target = parts[0], parts[1]
hdrs = {}
for ln in lines[1:]:
if ":" in ln:
k, v = ln.split(":", 1)
hdrs[k.strip().lower()] = v.strip()
if method != "CONNECT":
from urllib.parse import urlsplit
try:
u = urlsplit(target)
host, port = u.hostname, u.port or 80
path = (u.path or "/") + (("?" + u.query) if u.query else "")
except Exception:
writer.write(b"HTTP/1.1 400 Bad Request\r\n\r\n")
writer.close()
return
fwd = {k: v for k, v in hdrs.items() if k != "proxy-connection"}
fwd["host"] = host
req = "GET %s HTTP/1.1\r\n" % path + "".join("%s: %s\r\n" % (k, v) for k, v in fwd.items()) + "\r\n"
try:
r, w = await asyncio.wait_for(
asyncio.open_connection(host, port, local_addr=(next(CYCLE), 0)), timeout=25)
except Exception:
writer.write(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
writer.close()
return
w.write(req.encode("latin-1"))
await w.drain()
while True:
chunk = await r.read(65536)
if not chunk:
break
writer.write(chunk)
await writer.drain()
w.close()
writer.close()
return
sticky = None
if USER:
got = hdrs.get("proxy-authorization", "")
user_part = ""
if got.startswith("Basic "):
try:
user_part = base64.b64decode(got[6:]).decode("latin-1").split(":", 1)[0]
except Exception:
user_part = ""
base_user = user_part.split("-", 1)[0]
if "-" in user_part:
try:
sticky = int(user_part.rsplit("-", 1)[1])
except Exception:
sticky = None
want = "Basic " + base64.b64encode(("%s:%s" % (USER, PASS)).encode()).decode()
if got != want and base_user != USER:
writer.write(b"HTTP/1.1 407 Proxy Authentication Required\r\n"
b"Proxy-Authenticate: Basic realm=\"proxy\"\r\n\r\n")
await writer.drain()
writer.close()
return
host, _, port = target.rpartition(":")
port = int(port or 443)
order = list(IPS)
if sticky is not None:
first = IPS[sticky % len(IPS)]
order = [first] + [x for x in IPS if x != first]
remote = None
for i in range(len(order)):
src = order[i] if sticky is not None else next(CYCLE)
if FAILS.get(src, 0) >= 3:
continue
try:
remote = await asyncio.wait_for(
asyncio.open_connection(host, port, local_addr=(src, 0)), timeout=20)
break
except Exception:
FAILS[src] = FAILS.get(src, 0) + 1
remote = None
if remote is None:
writer.write(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
await writer.drain()
writer.close()
return
r, w = remote
writer.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
await writer.drain()
await asyncio.gather(pipe(reader, w), pipe(r, writer))
async def main():
global IPS, CYCLE, USER, PASS
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=8888)
ap.add_argument("--bind", default="0.0.0.0")
ap.add_argument("--user", default="")
ap.add_argument("--pass", dest="password", default="")
ap.add_argument("--ips", required=True, help="comma separated source IPs on this host")
a = ap.parse_args()
IPS = [x.strip() for x in a.ips.split(",") if x.strip()]
CYCLE = itertools.cycle(IPS)
USER, PASS = a.user, a.password
srv = await asyncio.start_server(handle, a.bind, a.port, backlog=512)
print("listening %s:%d ips=%s" % (a.bind, a.port, IPS), flush=True)
async with srv:
await srv.serve_forever()
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
sys.exit(0)