Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sqlmapproject
GitHub Repository: sqlmapproject/sqlmap
Path: blob/master/thirdparty/socks/socks.py
2992 views
1
#!/usr/bin/env python
2
3
"""SocksiPy - Python SOCKS module.
4
Version 1.00
5
6
Copyright 2006 Dan-Haim. All rights reserved.
7
8
Redistribution and use in source and binary forms, with or without modification,
9
are permitted provided that the following conditions are met:
10
1. Redistributions of source code must retain the above copyright notice, this
11
list of conditions and the following disclaimer.
12
2. Redistributions in binary form must reproduce the above copyright notice,
13
this list of conditions and the following disclaimer in the documentation
14
and/or other materials provided with the distribution.
15
3. Neither the name of Dan Haim nor the names of his contributors may be used
16
to endorse or promote products derived from this software without specific
17
prior written permission.
18
19
THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
20
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
22
EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
25
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
27
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.
28
29
30
This module provides a standard socket-like interface for Python
31
for tunneling connections through SOCKS proxies.
32
33
"""
34
35
"""
36
Minor modifications made by Miroslav Stampar (https://sqlmap.org)
37
for patching DNS-leakage occuring in socket.create_connection()
38
39
Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
40
for use in PyLoris (http://pyloris.sourceforge.net/)
41
42
Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
43
mainly to merge bug fixes found in Sourceforge
44
45
"""
46
47
import socket
48
import struct
49
50
PROXY_TYPE_SOCKS4 = 1
51
PROXY_TYPE_SOCKS5 = 2
52
PROXY_TYPE_HTTP = 3
53
54
_defaultproxy = None
55
socket._orig_socket = _orgsocket = _orig_socket = socket.socket
56
_orgcreateconnection = socket.create_connection
57
58
class ProxyError(Exception): pass
59
class GeneralProxyError(ProxyError): pass
60
class Socks5AuthError(ProxyError): pass
61
class Socks5Error(ProxyError): pass
62
class Socks4Error(ProxyError): pass
63
class HTTPError(ProxyError): pass
64
65
_generalerrors = ("success",
66
"invalid data",
67
"not connected",
68
"not available",
69
"bad proxy type",
70
"bad input")
71
72
_socks5errors = ("succeeded",
73
"general SOCKS server failure",
74
"connection not allowed by ruleset",
75
"Network unreachable",
76
"Host unreachable",
77
"Connection refused",
78
"TTL expired",
79
"Command not supported",
80
"Address type not supported",
81
"Unknown error")
82
83
_socks5autherrors = ("succeeded",
84
"authentication is required",
85
"all offered authentication methods were rejected",
86
"unknown username or invalid password",
87
"unknown error")
88
89
_socks4errors = ("request granted",
90
"request rejected or failed",
91
"request rejected because SOCKS server cannot connect to identd on the client",
92
"request rejected because the client program and identd report different user-ids",
93
"unknown error")
94
95
def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
96
"""setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
97
Sets a default proxy which all further socksocket objects will use,
98
unless explicitly changed.
99
"""
100
global _defaultproxy
101
_defaultproxy = (proxytype, addr, port, rdns, username, password)
102
103
def wrapmodule(module):
104
"""wrapmodule(module)
105
Attempts to replace a module's socket library with a SOCKS socket. Must set
106
a default proxy using setdefaultproxy(...) first.
107
This will only work on modules that import socket directly into the namespace;
108
most of the Python Standard Library falls into this category.
109
"""
110
if _defaultproxy != None:
111
module.socket.socket = socksocket
112
if _defaultproxy[0] == PROXY_TYPE_SOCKS4:
113
# Note: unable to prevent DNS leakage in SOCKS4 (Reference: https://security.stackexchange.com/a/171280)
114
pass
115
else:
116
module.socket.create_connection = create_connection
117
else:
118
raise GeneralProxyError((4, "no proxy specified"))
119
120
def unwrapmodule(module):
121
module.socket.socket = _orgsocket
122
module.socket.create_connection = _orgcreateconnection
123
124
class socksocket(socket.socket):
125
"""socksocket([family[, type[, proto]]]) -> socket object
126
Open a SOCKS enabled socket. The parameters are the same as
127
those of the standard socket init. In order for SOCKS to work,
128
you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
129
"""
130
131
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
132
_orgsocket.__init__(self, family, type, proto, _sock)
133
if _defaultproxy != None:
134
self.__proxy = _defaultproxy
135
else:
136
self.__proxy = (None, None, None, None, None, None)
137
self.__proxysockname = None
138
self.__proxypeername = None
139
140
def __recvall(self, count):
141
"""__recvall(count) -> data
142
Receive EXACTLY the number of bytes requested from the socket.
143
Blocks until the required number of bytes have been received.
144
"""
145
data = self.recv(count)
146
while len(data) < count:
147
d = self.recv(count-len(data))
148
if not d: raise GeneralProxyError((0, "connection closed unexpectedly"))
149
data = data + d
150
return data
151
152
def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
153
"""setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
154
Sets the proxy to be used.
155
proxytype - The type of the proxy to be used. Three types
156
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
157
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
158
addr - The address of the server (IP or DNS).
159
port - The port of the server. Defaults to 1080 for SOCKS
160
servers and 8080 for HTTP proxy servers.
161
rdns - Should DNS queries be preformed on the remote side
162
(rather than the local side). The default is True.
163
Note: This has no effect with SOCKS4 servers.
164
username - Username to authenticate with to the server.
165
The default is no authentication.
166
password - Password to authenticate with to the server.
167
Only relevant when username is also provided.
168
"""
169
self.__proxy = (proxytype, addr, port, rdns, username, password)
170
171
def __negotiatesocks5(self, destaddr, destport):
172
"""__negotiatesocks5(self,destaddr,destport)
173
Negotiates a connection through a SOCKS5 server.
174
"""
175
# First we'll send the authentication packages we support.
176
if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
177
# The username/password details were supplied to the
178
# setproxy method so we support the USERNAME/PASSWORD
179
# authentication (in addition to the standard none).
180
self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02))
181
else:
182
# No username/password were entered, therefore we
183
# only support connections with no authentication.
184
self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00))
185
# We'll receive the server's response to determine which
186
# method was selected
187
chosenauth = self.__recvall(2)
188
if chosenauth[0:1] != b'\x05':
189
self.close()
190
raise GeneralProxyError((1, _generalerrors[1]))
191
# Check the chosen authentication method
192
if chosenauth[1:2] == b'\x00':
193
# No authentication is required
194
pass
195
elif chosenauth[1:2] == b'\x02':
196
# Okay, we need to perform a basic username/password
197
# authentication.
198
self.sendall(b'\x01' + chr(len(self.__proxy[4])).encode() + self.__proxy[4].encode() + chr(len(self.__proxy[5])).encode() + self.__proxy[5].encode())
199
authstat = self.__recvall(2)
200
if authstat[0:1] != b'\x01':
201
# Bad response
202
self.close()
203
raise GeneralProxyError((1, _generalerrors[1]))
204
if authstat[1:2] != b'\x00':
205
# Authentication failed
206
self.close()
207
raise Socks5AuthError((3, _socks5autherrors[3]))
208
# Authentication succeeded
209
else:
210
# Reaching here is always bad
211
self.close()
212
if chosenauth[1:2] == b'\xff':
213
raise Socks5AuthError((2, _socks5autherrors[2]))
214
else:
215
raise GeneralProxyError((1, _generalerrors[1]))
216
# Now we can request the actual connection
217
req = struct.pack('BBB', 0x05, 0x01, 0x00)
218
# If the given destination address is an IP address, we'll
219
# use the IPv4 address request even if remote resolving was specified.
220
try:
221
ipaddr = socket.inet_aton(destaddr)
222
req = req + b'\x01' + ipaddr
223
except socket.error:
224
# Well it's not an IP number, so it's probably a DNS name.
225
if self.__proxy[3]:
226
# Resolve remotely
227
ipaddr = None
228
req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + (destaddr if isinstance(destaddr, bytes) else destaddr.encode())
229
else:
230
# Resolve locally
231
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
232
req = req + chr(0x01).encode() + ipaddr
233
req = req + struct.pack(">H", destport)
234
self.sendall(req)
235
# Get the response
236
resp = self.__recvall(4)
237
if resp[0:1] != chr(0x05).encode():
238
self.close()
239
raise GeneralProxyError((1, _generalerrors[1]))
240
elif resp[1:2] != chr(0x00).encode():
241
# Connection failed
242
self.close()
243
if ord(resp[1:2])<=8:
244
raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])]))
245
else:
246
raise Socks5Error((9, _socks5errors[9]))
247
# Get the bound address/port
248
elif resp[3:4] == chr(0x01).encode():
249
boundaddr = self.__recvall(4)
250
elif resp[3:4] == chr(0x03).encode():
251
resp = resp + self.recv(1)
252
boundaddr = self.__recvall(ord(resp[4:5]))
253
else:
254
self.close()
255
raise GeneralProxyError((1,_generalerrors[1]))
256
boundport = struct.unpack(">H", self.__recvall(2))[0]
257
self.__proxysockname = (boundaddr, boundport)
258
if ipaddr != None:
259
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
260
else:
261
self.__proxypeername = (destaddr, destport)
262
263
def getproxysockname(self):
264
"""getsockname() -> address info
265
Returns the bound IP address and port number at the proxy.
266
"""
267
return self.__proxysockname
268
269
def getproxypeername(self):
270
"""getproxypeername() -> address info
271
Returns the IP and port number of the proxy.
272
"""
273
return _orgsocket.getpeername(self)
274
275
def getpeername(self):
276
"""getpeername() -> address info
277
Returns the IP address and port number of the destination
278
machine (note: getproxypeername returns the proxy)
279
"""
280
return self.__proxypeername
281
282
def __negotiatesocks4(self,destaddr,destport):
283
"""__negotiatesocks4(self,destaddr,destport)
284
Negotiates a connection through a SOCKS4 server.
285
"""
286
# Check if the destination address provided is an IP address
287
rmtrslv = False
288
try:
289
ipaddr = socket.inet_aton(destaddr)
290
except socket.error:
291
# It's a DNS name. Check where it should be resolved.
292
if self.__proxy[3]:
293
ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01)
294
rmtrslv = True
295
else:
296
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
297
# Construct the request packet
298
req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
299
# The username parameter is considered userid for SOCKS4
300
if self.__proxy[4] != None:
301
req = req + self.__proxy[4]
302
req = req + chr(0x00).encode()
303
# DNS name if remote resolving is required
304
# NOTE: This is actually an extension to the SOCKS4 protocol
305
# called SOCKS4A and may not be supported in all cases.
306
if rmtrslv:
307
req = req + destaddr + chr(0x00).encode()
308
self.sendall(req)
309
# Get the response from the server
310
resp = self.__recvall(8)
311
if resp[0:1] != chr(0x00).encode():
312
# Bad data
313
self.close()
314
raise GeneralProxyError((1,_generalerrors[1]))
315
if resp[1:2] != chr(0x5A).encode():
316
# Server returned an error
317
self.close()
318
if ord(resp[1:2]) in (91, 92, 93):
319
self.close()
320
raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90]))
321
else:
322
raise Socks4Error((94, _socks4errors[4]))
323
# Get the bound address/port
324
self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0])
325
if rmtrslv != None:
326
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
327
else:
328
self.__proxypeername = (destaddr, destport)
329
330
def __negotiatehttp(self, destaddr, destport):
331
"""__negotiatehttp(self,destaddr,destport)
332
Negotiates a connection through an HTTP server.
333
"""
334
# If we need to resolve locally, we do this now
335
if not self.__proxy[3]:
336
addr = socket.gethostbyname(destaddr)
337
else:
338
addr = destaddr
339
self.sendall(("CONNECT " + addr + ":" + str(destport) + " HTTP/1.1\r\n" + "Host: " + destaddr + "\r\n\r\n").encode())
340
# We read the response until we get the string "\r\n\r\n"
341
resp = self.recv(1)
342
while resp.find("\r\n\r\n".encode()) == -1:
343
resp = resp + self.recv(1)
344
# We just need the first line to check if the connection
345
# was successful
346
statusline = resp.splitlines()[0].split(" ".encode(), 2)
347
if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
348
self.close()
349
raise GeneralProxyError((1, _generalerrors[1]))
350
try:
351
statuscode = int(statusline[1])
352
except ValueError:
353
self.close()
354
raise GeneralProxyError((1, _generalerrors[1]))
355
if statuscode != 200:
356
self.close()
357
raise HTTPError((statuscode, statusline[2]))
358
self.__proxysockname = ("0.0.0.0", 0)
359
self.__proxypeername = (addr, destport)
360
361
def connect(self, destpair):
362
"""connect(self, despair)
363
Connects to the specified destination through a proxy.
364
destpar - A tuple of the IP/DNS address and the port number.
365
(identical to socket's connect).
366
To select the proxy server use setproxy().
367
"""
368
# Do a minimal input check first
369
if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int):
370
raise GeneralProxyError((5, _generalerrors[5]))
371
if self.__proxy[0] == PROXY_TYPE_SOCKS5:
372
if self.__proxy[2] != None:
373
portnum = self.__proxy[2]
374
else:
375
portnum = 1080
376
_orgsocket.connect(self, (self.__proxy[1], portnum))
377
self.__negotiatesocks5(destpair[0], destpair[1])
378
elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
379
if self.__proxy[2] != None:
380
portnum = self.__proxy[2]
381
else:
382
portnum = 1080
383
_orgsocket.connect(self,(self.__proxy[1], portnum))
384
self.__negotiatesocks4(destpair[0], destpair[1])
385
elif self.__proxy[0] == PROXY_TYPE_HTTP:
386
if self.__proxy[2] != None:
387
portnum = self.__proxy[2]
388
else:
389
portnum = 8080
390
_orgsocket.connect(self,(self.__proxy[1], portnum))
391
self.__negotiatehttp(destpair[0], destpair[1])
392
elif self.__proxy[0] == None:
393
_orgsocket.connect(self, (destpair[0], destpair[1]))
394
else:
395
raise GeneralProxyError((4, _generalerrors[4]))
396
397
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
398
source_address=None):
399
# Patched for a DNS-leakage
400
host, port = address
401
sock = None
402
try:
403
sock = socksocket(socket.AF_INET, socket.SOCK_STREAM)
404
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
405
sock.settimeout(timeout)
406
if source_address:
407
sock.bind(source_address)
408
sock.connect(address)
409
except socket.error:
410
if sock is not None:
411
sock.close()
412
raise
413
return sock
414
415