90 lines
2.6 KiB
Python
90 lines
2.6 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""zte_socks.py [port] — SOCKS5-прокси, весь egress через мобильный IP (bind 192.168.0.2).
|
|
Chrome: --proxy-server=socks5://127.0.0.1:1081
|
|
"""
|
|
import socket, struct, sys, threading
|
|
|
|
BIND_IP = "192.168.0.2"
|
|
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 1081
|
|
BUFS = 65536
|
|
|
|
|
|
def pipe(a, b):
|
|
try:
|
|
while True:
|
|
r, _, _ = __import__("select").select([a, b], [], [], 300)
|
|
if not r:
|
|
break
|
|
for s in r:
|
|
data = s.recv(BUFS)
|
|
if not data:
|
|
return
|
|
(b if s is a else a).sendall(data)
|
|
except Exception:
|
|
pass
|
|
finally:
|
|
for s in (a, b):
|
|
try:
|
|
s.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def recv_exact(c, n):
|
|
buf = b""
|
|
while len(buf) < n:
|
|
chunk = c.recv(n - len(buf))
|
|
if not chunk:
|
|
raise IOError("eof")
|
|
buf += chunk
|
|
return buf
|
|
|
|
|
|
def handle(c):
|
|
try:
|
|
ver, n = recv_exact(c, 2)
|
|
recv_exact(c, n) # methods
|
|
c.sendall(b"\x05\x00") # no auth
|
|
ver, cmd, rsv, atyp = recv_exact(c, 4)
|
|
if atyp == 1:
|
|
host = socket.inet_ntoa(recv_exact(c, 4))
|
|
elif atyp == 3:
|
|
ln = recv_exact(c, 1)[0]
|
|
host = recv_exact(c, ln).decode()
|
|
elif atyp == 4:
|
|
host = socket.inet_ntop(socket.AF_INET6, recv_exact(c, 16))
|
|
else:
|
|
c.close(); return
|
|
port = struct.unpack("!H", recv_exact(c, 2))[0]
|
|
if cmd != 1:
|
|
c.sendall(b"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00"); c.close(); return
|
|
try:
|
|
up = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
up.settimeout(25)
|
|
up.bind((BIND_IP, 0))
|
|
up.connect((host, port))
|
|
up.settimeout(None)
|
|
except Exception:
|
|
c.sendall(b"\x05\x05\x00\x01\x00\x00\x00\x00\x00\x00"); c.close(); return
|
|
c.sendall(b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00")
|
|
threading.Thread(target=pipe, args=(c, up), daemon=True).start()
|
|
except Exception:
|
|
try:
|
|
c.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def main():
|
|
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
srv.bind(("127.0.0.1", PORT))
|
|
srv.listen(128)
|
|
print("socks5 on 127.0.0.1:%d -> bind %s" % (PORT, BIND_IP), flush=True)
|
|
while True:
|
|
c, _ = srv.accept()
|
|
threading.Thread(target=handle, args=(c,), daemon=True).start()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |