Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sqlmapproject
GitHub Repository: sqlmapproject/sqlmap
Path: blob/master/thirdparty/socks/socks.py
3554 views
1
#!/usr/bin/env python
2
3
"""SocksiPy - Python SOCKS module.
4
Version 1.01
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 functools
48
import socket
49
import struct
50
51
PROXY_TYPE_SOCKS4 = 1
52
PROXY_TYPE_SOCKS5 = 2
53
PROXY_TYPE_HTTP = 3
54
55
_defaultproxy = None
56
socket._orig_socket = _orgsocket = _orig_socket = socket.socket
57
_orgcreateconnection = socket.create_connection
58
59
class ProxyError(Exception): pass
60
class GeneralProxyError(ProxyError): pass
61
class Socks5AuthError(ProxyError): pass
62
class Socks5Error(ProxyError): pass
63
class Socks4Error(ProxyError): pass
64
class HTTPError(ProxyError): pass
65
66
_generalerrors = ("success",
67
"invalid data",
68
"not connected",
69
"not available",
70
"bad proxy type",
71
"bad input")
72
73
_socks5errors = ("succeeded",
74
"general SOCKS server failure",
75
"connection not allowed by ruleset",
76
"Network unreachable",
77
"Host unreachable",
78
"Connection refused",
79
"TTL expired",
80
"Command not supported",
81
"Address type not supported",
82
"Unknown error")
83
84
_socks5autherrors = ("succeeded",
85
"authentication is required",
86
"all offered authentication methods were rejected",
87
"unknown username or invalid password",
88
"unknown error")
89
90
_socks4errors = ("request granted",
91
"request rejected or failed",
92
"request rejected because SOCKS server cannot connect to identd on the client",
93
"request rejected because the client program and identd report different user-ids",
94
"unknown error")
95
96
def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
97
"""setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
98
Sets a default proxy which all further socksocket objects will use,
99
unless explicitly changed.
100
"""
101
global _defaultproxy
102
_defaultproxy = (proxytype, addr, port, rdns, username, password)
103
104
def wrapmodule(module):
105
"""wrapmodule(module)
106
Attempts to replace a module's socket library with a SOCKS socket. Must set
107
a default proxy using setdefaultproxy(...) first.
108
This will only work on modules that import socket directly into the namespace;
109
most of the Python Standard Library falls into this category.
110
"""
111
if _defaultproxy is not None:
112
_orig_socket_ctor = _orgsocket
113
114
@functools.wraps(_orig_socket_ctor)
115
def guarded_socket(*args, **kwargs):
116
# socket.socket([family[, type[, proto]]])
117
family = args[0] if len(args) > 0 else kwargs.get("family", socket.AF_INET)
118
stype = args[1] if len(args) > 1 else kwargs.get("type", socket.SOCK_STREAM)
119
120
# Normalize socket type by stripping flags (Py3.3+ may OR these in)
121
flags = 0
122
flags |= getattr(socket, "SOCK_CLOEXEC", 0)
123
flags |= getattr(socket, "SOCK_NONBLOCK", 0)
124
base_type = stype & ~flags
125
126
if family in (socket.AF_INET, getattr(socket, "AF_INET6", socket.AF_INET)) and base_type == socket.SOCK_STREAM:
127
return socksocket(*args, **kwargs)
128
129
# Fallback: don't proxy AF_UNIX / raw / etc.
130
return _orig_socket_ctor(*args, **kwargs)
131
132
module.socket.socket = guarded_socket
133
134
if _defaultproxy[0] == PROXY_TYPE_SOCKS4:
135
# Note: unable to prevent DNS leakage in SOCKS4 (Reference: https://security.stackexchange.com/a/171280)
136
pass
137
else:
138
module.socket.create_connection = create_connection
139
else:
140
raise GeneralProxyError((4, "no proxy specified"))
141
142
def unwrapmodule(module):
143
module.socket.socket = _orgsocket
144
module.socket.create_connection = _orgcreateconnection
145
146
class socksocket(socket.socket):
147
"""socksocket([family[, type[, proto]]]) -> socket object
148
Open a SOCKS enabled socket. The parameters are the same as
149
those of the standard socket init. In order for SOCKS to work,
150
you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
151
"""
152
153
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
154
_orgsocket.__init__(self, family, type, proto, _sock)
155
if _defaultproxy != None:
156
self.__proxy = _defaultproxy
157
else:
158
self.__proxy = (None, None, None, None, None, None)
159
self.__proxysockname = None
160
self.__proxypeername = None
161
162
def __recvall(self, count):
163
"""__recvall(count) -> data
164
Receive EXACTLY the number of bytes requested from the socket.
165
Blocks until the required number of bytes have been received.
166
"""
167
data = self.recv(count)
168
while len(data) < count:
169
d = self.recv(count-len(data))
170
if not d: raise GeneralProxyError((0, "connection closed unexpectedly"))
171
data = data + d
172
return data
173
174
def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
175
"""setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
176
Sets the proxy to be used.
177
proxytype - The type of the proxy to be used. Three types
178
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
179
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
180
addr - The address of the server (IP or DNS).
181
port - The port of the server. Defaults to 1080 for SOCKS
182
servers and 8080 for HTTP proxy servers.
183
rdns - Should DNS queries be preformed on the remote side
184
(rather than the local side). The default is True.
185
Note: This has no effect with SOCKS4 servers.
186
username - Username to authenticate with to the server.
187
The default is no authentication.
188
password - Password to authenticate with to the server.
189
Only relevant when username is also provided.
190
"""
191
self.__proxy = (proxytype, addr, port, rdns, username, password)
192
193
def __negotiatesocks5(self, destaddr, destport):
194
"""__negotiatesocks5(self,destaddr,destport)
195
Negotiates a connection through a SOCKS5 server.
196
"""
197
# First we'll send the authentication packages we support.
198
if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
199
# The username/password details were supplied to the
200
# setproxy method so we support the USERNAME/PASSWORD
201
# authentication (in addition to the standard none).
202
self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02))
203
else:
204
# No username/password were entered, therefore we
205
# only support connections with no authentication.
206
self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00))
207
# We'll receive the server's response to determine which
208
# method was selected
209
chosenauth = self.__recvall(2)
210
if chosenauth[0:1] != b'\x05':
211
self.close()
212
raise GeneralProxyError((1, _generalerrors[1]))
213
# Check the chosen authentication method
214
if chosenauth[1:2] == b'\x00':
215
# No authentication is required
216
pass
217
elif chosenauth[1:2] == b'\x02':
218
# Okay, we need to perform a basic username/password
219
# authentication.
220
self.sendall(b'\x01' + chr(len(self.__proxy[4])).encode() + self.__proxy[4].encode() + chr(len(self.__proxy[5])).encode() + self.__proxy[5].encode())
221
authstat = self.__recvall(2)
222
if authstat[0:1] != b'\x01':
223
# Bad response
224
self.close()
225
raise GeneralProxyError((1, _generalerrors[1]))
226
if authstat[1:2] != b'\x00':
227
# Authentication failed
228
self.close()
229
raise Socks5AuthError((3, _socks5autherrors[3]))
230
# Authentication succeeded
231
else:
232
# Reaching here is always bad
233
self.close()
234
if chosenauth[1:2] == b'\xff':
235
raise Socks5AuthError((2, _socks5autherrors[2]))
236
else:
237
raise GeneralProxyError((1, _generalerrors[1]))
238
# Now we can request the actual connection
239
req = struct.pack('BBB', 0x05, 0x01, 0x00)
240
# If the given destination address is an IP address, we'll
241
# use the IPv4 address request even if remote resolving was specified.
242
try:
243
ipaddr = socket.inet_aton(destaddr)
244
req = req + b'\x01' + ipaddr
245
except socket.error:
246
# Well it's not an IP number, so it's probably a DNS name.
247
if self.__proxy[3]:
248
# Resolve remotely
249
ipaddr = None
250
req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + (destaddr if isinstance(destaddr, bytes) else destaddr.encode())
251
else:
252
# Resolve locally
253
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
254
req = req + chr(0x01).encode() + ipaddr
255
req = req + struct.pack(">H", destport)
256
self.sendall(req)
257
# Get the response
258
resp = self.__recvall(4)
259
if resp[0:1] != chr(0x05).encode():
260
self.close()
261
raise GeneralProxyError((1, _generalerrors[1]))
262
elif resp[1:2] != chr(0x00).encode():
263
# Connection failed
264
self.close()
265
if ord(resp[1:2])<=8:
266
raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])]))
267
else:
268
raise Socks5Error((9, _socks5errors[9]))
269
# Get the bound address/port
270
elif resp[3:4] == chr(0x01).encode():
271
boundaddr = self.__recvall(4)
272
elif resp[3:4] == chr(0x03).encode():
273
resp = resp + self.recv(1)
274
boundaddr = self.__recvall(ord(resp[4:5]))
275
else:
276
self.close()
277
raise GeneralProxyError((1,_generalerrors[1]))
278
boundport = struct.unpack(">H", self.__recvall(2))[0]
279
self.__proxysockname = (boundaddr, boundport)
280
if ipaddr != None:
281
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
282
else:
283
self.__proxypeername = (destaddr, destport)
284
285
def getproxysockname(self):
286
"""getsockname() -> address info
287
Returns the bound IP address and port number at the proxy.
288
"""
289
return self.__proxysockname
290
291
def getproxypeername(self):
292
"""getproxypeername() -> address info
293
Returns the IP and port number of the proxy.
294
"""
295
return _orgsocket.getpeername(self)
296
297
def getpeername(self):
298
"""getpeername() -> address info
299
Returns the IP address and port number of the destination
300
machine (note: getproxypeername returns the proxy)
301
"""
302
return self.__proxypeername
303
304
def __negotiatesocks4(self,destaddr,destport):
305
"""__negotiatesocks4(self,destaddr,destport)
306
Negotiates a connection through a SOCKS4 server.
307
"""
308
# Check if the destination address provided is an IP address
309
rmtrslv = False
310
try:
311
ipaddr = socket.inet_aton(destaddr)
312
except socket.error:
313
# It's a DNS name. Check where it should be resolved.
314
if self.__proxy[3]:
315
ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01)
316
rmtrslv = True
317
else:
318
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
319
# Construct the request packet
320
req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
321
# The username parameter is considered userid for SOCKS4
322
if self.__proxy[4] != None:
323
req = req + self.__proxy[4]
324
req = req + chr(0x00).encode()
325
# DNS name if remote resolving is required
326
# NOTE: This is actually an extension to the SOCKS4 protocol
327
# called SOCKS4A and may not be supported in all cases.
328
if rmtrslv:
329
req = req + destaddr + chr(0x00).encode()
330
self.sendall(req)
331
# Get the response from the server
332
resp = self.__recvall(8)
333
if resp[0:1] != chr(0x00).encode():
334
# Bad data
335
self.close()
336
raise GeneralProxyError((1,_generalerrors[1]))
337
if resp[1:2] != chr(0x5A).encode():
338
# Server returned an error
339
self.close()
340
if ord(resp[1:2]) in (91, 92, 93):
341
self.close()
342
raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90]))
343
else:
344
raise Socks4Error((94, _socks4errors[4]))
345
# Get the bound address/port
346
self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0])
347
if rmtrslv != None:
348
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
349
else:
350
self.__proxypeername = (destaddr, destport)
351
352
def __negotiatehttp(self, destaddr, destport):
353
"""__negotiatehttp(self,destaddr,destport)
354
Negotiates a connection through an HTTP server.
355
"""
356
# If we need to resolve locally, we do this now
357
if not self.__proxy[3]:
358
addr = socket.gethostbyname(destaddr)
359
else:
360
addr = destaddr
361
self.sendall(("CONNECT " + addr + ":" + str(destport) + " HTTP/1.1\r\n" + "Host: " + destaddr + "\r\n\r\n").encode())
362
# We read the response until we get the string "\r\n\r\n"
363
resp = self.recv(1)
364
while resp.find("\r\n\r\n".encode()) == -1:
365
resp = resp + self.recv(1)
366
# We just need the first line to check if the connection
367
# was successful
368
statusline = resp.splitlines()[0].split(" ".encode(), 2)
369
if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
370
self.close()
371
raise GeneralProxyError((1, _generalerrors[1]))
372
try:
373
statuscode = int(statusline[1])
374
except ValueError:
375
self.close()
376
raise GeneralProxyError((1, _generalerrors[1]))
377
if statuscode != 200:
378
self.close()
379
raise HTTPError((statuscode, statusline[2]))
380
self.__proxysockname = ("0.0.0.0", 0)
381
self.__proxypeername = (addr, destport)
382
383
def connect(self, destpair):
384
"""connect(self, despair)
385
Connects to the specified destination through a proxy.
386
destpar - A tuple of the IP/DNS address and the port number.
387
(identical to socket's connect).
388
To select the proxy server use setproxy().
389
"""
390
# Do a minimal input check first
391
if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int):
392
raise GeneralProxyError((5, _generalerrors[5]))
393
if self.__proxy[0] == PROXY_TYPE_SOCKS5:
394
if self.__proxy[2] != None:
395
portnum = self.__proxy[2]
396
else:
397
portnum = 1080
398
_orgsocket.connect(self, (self.__proxy[1], portnum))
399
self.__negotiatesocks5(destpair[0], destpair[1])
400
elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
401
if self.__proxy[2] != None:
402
portnum = self.__proxy[2]
403
else:
404
portnum = 1080
405
_orgsocket.connect(self,(self.__proxy[1], portnum))
406
self.__negotiatesocks4(destpair[0], destpair[1])
407
elif self.__proxy[0] == PROXY_TYPE_HTTP:
408
if self.__proxy[2] != None:
409
portnum = self.__proxy[2]
410
else:
411
portnum = 8080
412
_orgsocket.connect(self,(self.__proxy[1], portnum))
413
self.__negotiatehttp(destpair[0], destpair[1])
414
elif self.__proxy[0] == None:
415
_orgsocket.connect(self, (destpair[0], destpair[1]))
416
else:
417
raise GeneralProxyError((4, _generalerrors[4]))
418
419
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
420
source_address=None):
421
# Patched for a DNS-leakage
422
host, port = address
423
sock = None
424
try:
425
sock = socksocket(socket.AF_INET, socket.SOCK_STREAM)
426
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
427
sock.settimeout(timeout)
428
if source_address:
429
sock.bind(source_address)
430
sock.connect(address)
431
except socket.error:
432
if sock is not None:
433
sock.close()
434
raise
435
return sock
436
437