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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
|
import asyncio
import struct
import logging
import socket
import enum
import ssl
class Command(enum.IntEnum):
"""
SOCKS5 request command type
"""
CONNECT = 0x01
BIND = 0x02
UDP_ASSOCIATE = 0x03
class AddressType(enum.IntEnum):
"""
SOCKS5 address type
"""
IPV4 = 0x01
DOMAINE_NAME = 0x03
IPV6 = 0x04
class BaseTunnelProtocol(asyncio.StreamReaderProtocol):
def __init__(self):
loop = asyncio.get_running_loop()
reader = asyncio.StreamReader(loop=loop)
super().__init__(reader, loop=loop)
self.reader = reader
self.loop = loop
self.transport = None
self._shutdown = asyncio.Event()
self.logger = logging.getLogger('aiotunnel.protocol.BaseTunnelProtocol')
def reader(self):
return self.reader
async def read(self, fmt):
"""
Unpacks data from the input stream
:param fmt: Data format
:return: The unpacked data
"""
return struct.unpack(fmt, await self.reader.read(struct.calcsize(fmt)))
def write(self, fmt, *argv):
"""
Packs data to the writer
:param fmt: Pack format
:param argv: Pack content
"""
self.transport.write(struct.pack(fmt, *argv))
def connection_made(self, transport):
self.transport = transport
self.transport.set_write_buffer_limits(0)
sock = transport.get_extra_info('socket')
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
super().connection_made(transport)
def connection_lost(self, exc):
self.logger.debug('The server closed the connection')
self.transport.close()
super().connection_lost(exc)
def eof_received(self):
self.logger.debug('No more data to receive')
self.transport.close()
super().eof_received()
def close(self):
self._shutdown.set()
self.transport.close()
# super().close()
# async def wait_closed(self):
# await self.transport.wait_closed()
class LocalOpenRemoteProtocol(BaseTunnelProtocol):
def __init__(self, transport, loop):
super().__init__()
self.client_transport = transport
self.logger = logging.getLogger('aiotunnel.protocol.LocalOpenRemoteProtocol')
def write(self, data):
self.transport.write(data)
async def drain(self):
await self.transport.drain()
def connection_made(self, transport):
super().connection_made(transport)
self.loop.create_task(self.async_write_data())
async def async_write_data(self):
while not self._shutdown.is_set():
data = await self.reader.read(4096)
if not data:
break
self.client_transport.write(data)
class ServerProtocol(BaseTunnelProtocol):
def __init__(self, on_conn_lost=None):
super().__init__()
self.on_conn_lost = on_conn_lost
self.logger = logging.getLogger('aiotunnel.protocol.ServerProtocol')
def connection_made(self, transport):
super().connection_made(transport)
self.loop.create_task(self.async_write_data())
def data_received(self, data):
super().data_received(data)
async def async_write_data(self):
while not self._shutdown.is_set():
addr_type, domain_length = await self.read('!BB')
if addr_type == 1:
address_bytes = await self.reader.read(4)
address = socket.inet_ntoa(address_bytes)
elif addr_type == 3:
address = await self.reader.read(domain_length)
address = socket.gethostbyname(address)
port_data = await self.read('!H')
port = port_data[0]
ssl_ctx = ssl.create_default_context()
debug = True
if debug:
ssl_ctx = None
self.logger.debug(f'Open connection {address}:{port}')
protocol = LocalOpenRemoteProtocol(self.transport, self.loop)
remote_reader, remote_writer = await self.loop.create_connection(
lambda: protocol, address, port)
writer = asyncio.StreamWriter(remote_reader, protocol, protocol.reader, self.loop)
self.logger.debug(f'Opened {address}:{port}')
# Get our own details
server_socket = remote_reader.get_extra_info("socket")
bind_address, bind_port = server_socket.getsockname()[:2]
bind_address = socket.inet_pton(server_socket.family, bind_address)
if server_socket.family == socket.AF_INET:
address_type = AddressType.IPV4
elif server_socket.family == socket.AF_INET6:
address_type = AddressType.IPV6
data = await self.reader.read(4096)
while data:
remote_writer.write(data)
# await remote_writer.drain()
data = await self.reader.read(4096)
writer.close()
await writer.wait_closed()
self.close()
class LocalTunnelProtocol(BaseTunnelProtocol):
def __init__(self, server_hostname, server_port, on_conn_lost=None):
super().__init__()
self.server_hostname = server_hostname
self.server_port = server_port
self.write_queue = asyncio.Queue()
self.on_conn_lost = on_conn_lost
self.logger = logging.getLogger('aiotunnel.protocol.LocalTunnelProtocol')
def connection_made(self, transport):
super().connection_made(transport)
self.loop.create_task(self.async_write_data())
async def async_write_data(self):
while not self._shutdown.is_set():
try:
version, nb_methods = await self.read('!BB')
except struct.error:
self.write('!BB', 0x05, 0x01)
self.close()
return
if version != 0x05:
self.write('!BB', 0x05, 0x01)
self.close()
return
# Ignore the methods
await self.reader.read(nb_methods)
# Sends the server "selected" method: no authentication
self.write('!BB', version, 0x00)
# Read the header of the request
version, cmd, _, address_type = await self.read('!BBBB')
domain_length = 0
if cmd != 0x01:
write_reply(ReplyCode.COMMAND_NOT_SUPPORTED)
self.close()
return
if address_type == AddressType.IPV4:
# IPv4 connection
raw_address = await self.reader.read(4)
address = socket.inet_ntop(socket.AF_INET, raw_address)
elif address_type == AddressType.IPV6:
# IPv6 connection
raw_address = await self.reader.read(16)
address = socket.inet_ntop(socket.AF_INET6, raw_address)
elif address_type == AddressType.DOMAINE_NAME:
# DNS resolution
domain_length = (await self.read('!B'))[0]
hostname = (await self.read("!{}s".format(domain_length)))[0]
# address = socket.gethostbyname(hostname)
address = hostname
else:
write_reply(ReplyCode.ADDRESS_NOT_SUPPORTED)
self.close()
raise IOError("Unhandled address type: {:x}".format(address_type))
port = (await self.read('!H'))[0]
if type(address) == str:
address = address.encode('utf-8')
addr_pack_fro_remote = struct.pack(f'!BB{domain_length}sH', address_type, domain_length, address, port)
# transport, _ = await self.loop.create_connection(
# lambda: LocalOpenRemoteProtocol, host, port)
ssl_ctx = ssl.create_default_context()
debug = True
if debug:
ssl_ctx = None
self.logger.debug(f'Open connection {address}:{port}')
protocol = LocalOpenRemoteProtocol(self.transport, self.loop)
remote_reader, remote_writer = await self.loop.create_connection(
lambda: protocol, self.server_hostname, self.server_port, ssl=ssl_ctx)
writer = asyncio.StreamWriter(remote_reader, protocol, protocol.reader, self.loop)
self.logger.debug(f'Opened {address}:{port}')
# Get our own details
server_socket = remote_reader.get_extra_info("socket")
bind_address, bind_port = server_socket.getsockname()[:2]
bind_address = socket.inet_pton(server_socket.family, bind_address)
if server_socket.family == socket.AF_INET:
address_type = AddressType.IPV4
elif server_socket.family == socket.AF_INET6:
address_type = AddressType.IPV6
self.write('!BBBB', 0x05, 0x00, 0x00, address_type)
self.transport.write(bind_address)
self.write('!H', port)
remote_writer.write(addr_pack_fro_remote)
data = await self.reader.read(4096)
while data:
remote_writer.write(data)
data = await self.reader.read(4096)
writer.close()
await writer.wait_closed()
|