File size: 3,754 Bytes
fa18079
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env python3
"""
SOCKS5 proxy bridge: listens on 1080, forwards via HTTP CONNECT to upstream proxy.
Upstream = tinyproxy through Cloudflare quick tunnel.
"""
import asyncio, struct, logging, os
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
log = logging.getLogger('socks5_bridge')

UPSTREAM_PROXY = os.environ.get('UPSTREAM_PROXY', 'https://relying-technology-word-talented.trycloudflare.com')
LISTEN_HOST = '127.0.0.1'
LISTEN_PORT = 1080

async def relay(reader, writer):
    try:
        while True:
            data = await reader.read(65536)
            if not data:
                break
            writer.write(data)
            await writer.drain()
    except:
        pass
    finally:
        writer.close()

async def handle_socks5(reader, writer):
    try:
        # SOCKS5 greeting
        ver, nmethods = struct.unpack('!BB', await reader.readexactly(2))
        methods = await reader.readexactly(nmethods)
        # No auth
        writer.write(b'\x05\x00')
        await writer.drain()

        # SOCKS5 request
        ver, cmd, rsv, atyp = struct.unpack('!BBBB', await reader.readexactly(4))
        if cmd != 1:  # Only CONNECT
            writer.write(b'\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00')
            writer.close()
            return

        if atyp == 1:  # IPv4
            addr = '.'.join(str(b) for b in await reader.readexactly(4))
        elif atyp == 3:  # Domain
            alen = (await reader.readexactly(1))[0]
            addr = (await reader.readexactly(alen)).decode()
        elif atyp == 4:  # IPv6
            addr = ':'.join('{:02x}{:02x}'.format(*b) for b in zip(*[iter(await reader.readexactly(16))]*2))
        else:
            writer.close()
            return

        port = struct.unpack('!H', await reader.readexactly(2))[0]
        target = f'{addr}:{port}'
        log.info(f'CONNECT {target}')

        # Connect to upstream proxy (CF tunnel -> tinyproxy)
        import ssl
        from urllib.parse import urlparse
        parsed = urlparse(UPSTREAM_PROXY)
        upstream_host = parsed.hostname
        upstream_port = parsed.port or 443

        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE

        loop = asyncio.get_event_loop()
        up_reader, up_writer = await asyncio.open_connection(
            upstream_host, upstream_port, ssl=ctx, server_hostname=upstream_host
        )

        # Send HTTP CONNECT to upstream proxy
        connect_req = f'CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n'
        up_writer.write(connect_req.encode())
        await up_writer.drain()

        # Read response
        response = await up_reader.readuntil(b'\r\n\r\n')
        resp_line = response.split(b'\r\n')[0].decode()
        log.info(f'Upstream response: {resp_line}')

        if '200' not in resp_line:
            # Failed
            writer.write(b'\x05\x05\x00\x01\x00\x00\x00\x00\x00\x00')
            writer.close()
            up_writer.close()
            return

        # Success - tell client
        writer.write(b'\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00')
        await writer.drain()

        # Relay both ways
        await asyncio.gather(relay(reader, up_writer), relay(up_reader, writer))
    except Exception as e:
        log.error(f'Error: {e}')
        try:
            writer.close()
        except:
            pass

async def main():
    server = await asyncio.start_server(handle_socks5, LISTEN_HOST, LISTEN_PORT)
    log.info(f'SOCKS5 bridge listening on {LISTEN_HOST}:{LISTEN_PORT}')
    log.info(f'Upstream proxy: {UPSTREAM_PROXY}')
    async with server:
        await server.serve_forever()

if __name__ == '__main__':
    asyncio.run(main())