forked from Tribler/tribler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.py
217 lines (175 loc) · 8.32 KB
/
connection.py
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
import logging
from asyncio import Protocol, ensure_future
from ipv8.messaging.serialization import PackError
from tribler.core.components.socks_servers.socks5.conversion import (
CommandRequest,
CommandResponse,
MethodsRequest,
MethodsResponse,
REP_COMMAND_NOT_SUPPORTED,
REP_SUCCEEDED,
REQ_CMD_BIND,
REQ_CMD_CONNECT,
REQ_CMD_UDP_ASSOCIATE,
SOCKS_VERSION,
socks5_serializer,
)
from tribler.core.components.socks_servers.socks5.udp_connection import SocksUDPConnection
class ConnectionState:
"""
Enumeration of possible SOCKS5 connection states
"""
BEFORE_METHOD_REQUEST = 'BEFORE_METHOD_REQUEST'
METHOD_REQUESTED = 'METHOD_REQUESTED'
CONNECTED = 'CONNECTED'
PROXY_REQUEST_RECEIVED = 'PROXY_REQUEST_RECEIVED'
PROXY_REQUEST_ACCEPTED = 'PROXY_REQUEST_ACCEPTED'
class Socks5Connection(Protocol):
"""
SOCKS5 TCP Connection handler
Supports a subset of the SOCKS5 protocol, no authentication and no support for TCP BIND requests
"""
def __init__(self, socksserver):
super().__init__()
self._logger = logging.getLogger(self.__class__.__name__)
self._logger.setLevel(logging.WARNING)
self.socksserver = socksserver
self.transport = None
self.connect_to = None
self.udp_connection = None
self.state = ConnectionState.BEFORE_METHOD_REQUEST
self.buffer = b''
self.destinations = {}
def connection_made(self, transport):
self.transport = transport
def data_received(self, data):
self.buffer = self.buffer + data
while len(self.buffer) > 0:
# We are at the initial state, so we expect a handshake request.
if self.state == ConnectionState.BEFORE_METHOD_REQUEST:
if not self._try_handshake():
break # Not enough bytes so wait till we got more
# We are connected so the
elif self.state == ConnectionState.CONNECTED:
if not self._try_request():
break # Not enough bytes so wait till we got more
elif self.connect_to:
if self.socksserver.output_stream is not None:
# Swallow the data in case the tunnel community has not started yet
self.socksserver.output_stream.on_socks5_tcp_data(self, self.connect_to, self.buffer)
self.buffer = b''
else:
self._logger.error("Throwing away buffer, not in CONNECTED or BEFORE_METHOD_REQUEST state")
self.buffer = b''
def _try_handshake(self):
"""
Try to read a HANDSHAKE request
:return: False if command could not been processes due to lack of bytes, True otherwise
"""
try:
request, offset = socks5_serializer.unpack_serializable(MethodsRequest, self.buffer)
except PackError:
# No (complete) HANDSHAKE received, so dont do anything
return False
# Consume the buffer
self.buffer = self.buffer[offset:]
# Only accept NO AUTH
if request.version != SOCKS_VERSION or 0x00 not in request.methods:
self._logger.error("Client has sent INVALID METHOD REQUEST")
self.buffer = ''
self.close()
else:
self._logger.info("Client has sent METHOD REQUEST")
# Respond that we would like to use NO AUTHENTICATION (0x00)
if self.state is not ConnectionState.CONNECTED:
response = socks5_serializer.pack_serializable(MethodsResponse(SOCKS_VERSION, 0))
self.transport.write(response)
# We are connected now, the next incoming message will be a REQUEST
self.state = ConnectionState.CONNECTED
return True
def _try_request(self):
"""
Try to consume a REQUEST message and respond whether we will accept the
request.
Will setup a TCP relay or an UDP socket to accommodate TCP RELAY and
UDP ASSOCIATE requests. After a TCP relay is set up the handler will
deactivate itself and change the Connection to a TcpRelayConnection.
Further data will be passed on to that handler.
:return: False if command could not been processes due to lack of bytes, True otherwise
"""
self._logger.debug("Client has sent PROXY REQUEST")
try:
request, offset = socks5_serializer.unpack_serializable(CommandRequest, self.buffer)
except PackError:
return False
self.buffer = self.buffer[offset:]
self.state = ConnectionState.PROXY_REQUEST_RECEIVED
try:
if request.cmd == REQ_CMD_UDP_ASSOCIATE:
ensure_future(self.on_udp_associate_request(request))
elif request.cmd == REQ_CMD_BIND:
payload = CommandResponse(SOCKS_VERSION, REP_SUCCEEDED, 0, ("127.0.0.1", 1081))
response = socks5_serializer.pack_serializable(payload)
self.transport.write(response)
self.state = ConnectionState.PROXY_REQUEST_ACCEPTED
elif request.cmd == REQ_CMD_CONNECT:
self._logger.info("Accepting TCP CONNECT request to %s:%d", *request.destination)
self.connect_to = request.destination
payload = CommandResponse(SOCKS_VERSION, REP_SUCCEEDED, 0, ("127.0.0.1", 1081))
response = socks5_serializer.pack_serializable(payload)
self.transport.write(response)
else:
self.deny_request(request, "CMD not recognized")
except:
payload = CommandResponse(SOCKS_VERSION, REP_COMMAND_NOT_SUPPORTED, 0, ("0.0.0.0", 0))
response = socks5_serializer.pack_serializable(payload)
self.transport.write(response)
self._logger.exception("Exception thrown, returning unsupported command response")
return True
def deny_request(self, request, reason):
"""
Deny SOCKS5 request
@param Request request: the request to deny
"""
self.state = ConnectionState.CONNECTED
payload = CommandResponse(SOCKS_VERSION, REP_COMMAND_NOT_SUPPORTED, 0, ("0.0.0.0", 0))
response = socks5_serializer.pack_serializable(payload)
self.transport.write(response)
self._logger.error(f"DENYING SOCKS5 request, reason: {reason}")
async def on_udp_associate_request(self, request):
# The DST.ADDR and DST.PORT fields contain the address and port that the client expects
# to use to send UDP datagrams on for the association. The server MAY use this information
# to limit access to the association.
self.udp_connection = SocksUDPConnection(self, request.destination)
await self.udp_connection.open()
ip, _ = self.transport.get_extra_info('sockname')
port = self.udp_connection.get_listen_port()
self._logger.info("Accepting UDP ASSOCIATE request to %s:%d (BIND addr %s:%d)", ip, port, *request.destination)
payload = CommandResponse(SOCKS_VERSION, REP_SUCCEEDED, 0, (ip, port))
response = socks5_serializer.pack_serializable(payload)
self.transport.write(response)
def circuit_dead(self, broken_circuit):
"""
When a circuit breaks and it affects our operation we should re-add the peers when a new circuit is available
@param Circuit broken_circuit: the circuit that has been broken
@return Set with destinations using this circuit
"""
affected_destinations = {destination for destination, tunnel_circuit
in self.destinations.items() if tunnel_circuit == broken_circuit}
counter = 0
for destination in affected_destinations:
if destination in self.destinations:
del self.destinations[destination]
counter += 1
if counter > 0:
self._logger.debug("Deleted %d peers from destination list", counter)
return affected_destinations
def connection_lost(self, _):
self.socksserver.connection_lost(self)
def close(self, reason='unspecified'):
self._logger.info("Closing session, reason %s", reason)
if self.udp_connection:
self.udp_connection.close()
self.udp_connection = None
if self.transport:
self.transport.close()