1 """SocksiPy - Python SOCKS module.
4 Copyright 2006 Dan-Haim. All rights reserved.
6 Redistribution and use in source and binary forms, with or without modification,
7 are permitted provided that the following conditions are met:
8 1. Redistributions of source code must retain the above copyright notice, this
9 list of conditions and the following disclaimer.
10 2. Redistributions in binary form must reproduce the above copyright notice,
11 this list of conditions and the following disclaimer in the documentation
12 and/or other materials provided with the distribution.
13 3. Neither the name of Dan Haim nor the names of his contributors may be used
14 to endorse or promote products derived from this software without specific
15 prior written permission.
17 THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
18 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
20 EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
23 OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE.
28 This module provides a standard socket-like interface for Python
29 for tunneling connections through SOCKS proxies.
35 Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
36 for use in PyLoris (http://pyloris.sourceforge.net/)
38 Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
39 mainly to merge bug fixes found in Sourceforge
47 if getattr(socket, 'socket', None) is None:
48 raise ImportError('socket.socket missing, proxy support unusable')
55 _orgsocket = socket.socket
57 class ProxyError(Exception): pass
58 class GeneralProxyError(ProxyError): pass
59 class Socks5AuthError(ProxyError): pass
60 class Socks5Error(ProxyError): pass
61 class Socks4Error(ProxyError): pass
62 class HTTPError(ProxyError): pass
64 _generalerrors = ("success",
71 _socks5errors = ("succeeded",
72 "general SOCKS server failure",
73 "connection not allowed by ruleset",
74 "Network unreachable",
78 "Command not supported",
79 "Address type not supported",
82 _socks5autherrors = ("succeeded",
83 "authentication is required",
84 "all offered authentication methods were rejected",
85 "unknown username or invalid password",
88 _socks4errors = ("request granted",
89 "request rejected or failed",
90 "request rejected because SOCKS server cannot connect to identd on the client",
91 "request rejected because the client program and identd report different user-ids",
94 def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
95 """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
96 Sets a default proxy which all further socksocket objects will use,
97 unless explicitly changed.
100 _defaultproxy = (proxytype, addr, port, rdns, username, password)
102 def wrapmodule(module):
103 """wrapmodule(module)
104 Attempts to replace a module's socket library with a SOCKS socket. Must set
105 a default proxy using setdefaultproxy(...) first.
106 This will only work on modules that import socket directly into the namespace;
107 most of the Python Standard Library falls into this category.
109 if _defaultproxy != None:
110 module.socket.socket = socksocket
112 raise GeneralProxyError((4, "no proxy specified"))
114 class socksocket(socket.socket):
115 """socksocket([family[, type[, proto]]]) -> socket object
116 Open a SOCKS enabled socket. The parameters are the same as
117 those of the standard socket init. In order for SOCKS to work,
118 you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
121 def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
122 _orgsocket.__init__(self, family, type, proto, _sock)
123 if _defaultproxy != None:
124 self.__proxy = _defaultproxy
126 self.__proxy = (None, None, None, None, None, None)
127 self.__proxysockname = None
128 self.__proxypeername = None
130 def __recvall(self, count):
131 """__recvall(count) -> data
132 Receive EXACTLY the number of bytes requested from the socket.
133 Blocks until the required number of bytes have been received.
135 data = self.recv(count)
136 while len(data) < count:
137 d = self.recv(count-len(data))
138 if not d: raise GeneralProxyError((0, "connection closed unexpectedly"))
142 def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
143 """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
144 Sets the proxy to be used.
145 proxytype - The type of the proxy to be used. Three types
146 are supported: PROXY_TYPE_SOCKS4 (including socks4a),
147 PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
148 addr - The address of the server (IP or DNS).
149 port - The port of the server. Defaults to 1080 for SOCKS
150 servers and 8080 for HTTP proxy servers.
151 rdns - Should DNS queries be preformed on the remote side
152 (rather than the local side). The default is True.
153 Note: This has no effect with SOCKS4 servers.
154 username - Username to authenticate with to the server.
155 The default is no authentication.
156 password - Password to authenticate with to the server.
157 Only relevant when username is also provided.
159 self.__proxy = (proxytype, addr, port, rdns, username, password)
161 def __negotiatesocks5(self, destaddr, destport):
162 """__negotiatesocks5(self,destaddr,destport)
163 Negotiates a connection through a SOCKS5 server.
165 # First we'll send the authentication packages we support.
166 if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
167 # The username/password details were supplied to the
168 # setproxy method so we support the USERNAME/PASSWORD
169 # authentication (in addition to the standard none).
170 self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02))
172 # No username/password were entered, therefore we
173 # only support connections with no authentication.
174 self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00))
175 # We'll receive the server's response to determine which
176 # method was selected
177 chosenauth = self.__recvall(2)
178 if chosenauth[0:1] != chr(0x05).encode():
180 raise GeneralProxyError((1, _generalerrors[1]))
181 # Check the chosen authentication method
182 if chosenauth[1:2] == chr(0x00).encode():
183 # No authentication is required
185 elif chosenauth[1:2] == chr(0x02).encode():
186 # Okay, we need to perform a basic username/password
188 self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5])
189 authstat = self.__recvall(2)
190 if authstat[0:1] != chr(0x01).encode():
193 raise GeneralProxyError((1, _generalerrors[1]))
194 if authstat[1:2] != chr(0x00).encode():
195 # Authentication failed
197 raise Socks5AuthError((3, _socks5autherrors[3]))
198 # Authentication succeeded
200 # Reaching here is always bad
202 if chosenauth[1] == chr(0xFF).encode():
203 raise Socks5AuthError((2, _socks5autherrors[2]))
205 raise GeneralProxyError((1, _generalerrors[1]))
206 # Now we can request the actual connection
207 req = struct.pack('BBB', 0x05, 0x01, 0x00)
208 # If the given destination address is an IP address, we'll
209 # use the IPv4 address request even if remote resolving was specified.
211 ipaddr = socket.inet_aton(destaddr)
212 req = req + chr(0x01).encode() + ipaddr
214 # Well it's not an IP number, so it's probably a DNS name.
218 req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr
221 ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
222 req = req + chr(0x01).encode() + ipaddr
223 req = req + struct.pack(">H", destport)
226 resp = self.__recvall(4)
227 if resp[0:1] != chr(0x05).encode():
229 raise GeneralProxyError((1, _generalerrors[1]))
230 elif resp[1:2] != chr(0x00).encode():
233 if ord(resp[1:2])<=8:
234 raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])]))
236 raise Socks5Error((9, _socks5errors[9]))
237 # Get the bound address/port
238 elif resp[3:4] == chr(0x01).encode():
239 boundaddr = self.__recvall(4)
240 elif resp[3:4] == chr(0x03).encode():
241 resp = resp + self.recv(1)
242 boundaddr = self.__recvall(ord(resp[4:5]))
245 raise GeneralProxyError((1,_generalerrors[1]))
246 boundport = struct.unpack(">H", self.__recvall(2))[0]
247 self.__proxysockname = (boundaddr, boundport)
249 self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
251 self.__proxypeername = (destaddr, destport)
253 def getproxysockname(self):
254 """getsockname() -> address info
255 Returns the bound IP address and port number at the proxy.
257 return self.__proxysockname
259 def getproxypeername(self):
260 """getproxypeername() -> address info
261 Returns the IP and port number of the proxy.
263 return _orgsocket.getpeername(self)
265 def getpeername(self):
266 """getpeername() -> address info
267 Returns the IP address and port number of the destination
268 machine (note: getproxypeername returns the proxy)
270 return self.__proxypeername
272 def __negotiatesocks4(self,destaddr,destport):
273 """__negotiatesocks4(self,destaddr,destport)
274 Negotiates a connection through a SOCKS4 server.
276 # Check if the destination address provided is an IP address
279 ipaddr = socket.inet_aton(destaddr)
281 # It's a DNS name. Check where it should be resolved.
283 ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01)
286 ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
287 # Construct the request packet
288 req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
289 # The username parameter is considered userid for SOCKS4
290 if self.__proxy[4] != None:
291 req = req + self.__proxy[4]
292 req = req + chr(0x00).encode()
293 # DNS name if remote resolving is required
294 # NOTE: This is actually an extension to the SOCKS4 protocol
295 # called SOCKS4A and may not be supported in all cases.
297 req = req + destaddr + chr(0x00).encode()
299 # Get the response from the server
300 resp = self.__recvall(8)
301 if resp[0:1] != chr(0x00).encode():
304 raise GeneralProxyError((1,_generalerrors[1]))
305 if resp[1:2] != chr(0x5A).encode():
306 # Server returned an error
308 if ord(resp[1:2]) in (91, 92, 93):
310 raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90]))
312 raise Socks4Error((94, _socks4errors[4]))
313 # Get the bound address/port
314 self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0])
316 self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
318 self.__proxypeername = (destaddr, destport)
320 def __negotiatehttp(self, destaddr, destport):
321 """__negotiatehttp(self,destaddr,destport)
322 Negotiates a connection through an HTTP server.
324 # If we need to resolve locally, we do this now
325 if not self.__proxy[3]:
326 addr = socket.gethostbyname(destaddr)
329 self.sendall(("CONNECT " + addr + ":" + str(destport) + " HTTP/1.1\r\n" + "Host: " + destaddr + "\r\n\r\n").encode())
330 # We read the response until we get the string "\r\n\r\n"
332 while resp.find("\r\n\r\n".encode()) == -1:
333 resp = resp + self.recv(1)
334 # We just need the first line to check if the connection
336 statusline = resp.splitlines()[0].split(" ".encode(), 2)
337 if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
339 raise GeneralProxyError((1, _generalerrors[1]))
341 statuscode = int(statusline[1])
344 raise GeneralProxyError((1, _generalerrors[1]))
345 if statuscode != 200:
347 raise HTTPError((statuscode, statusline[2]))
348 self.__proxysockname = ("0.0.0.0", 0)
349 self.__proxypeername = (addr, destport)
351 def connect(self, destpair):
352 """connect(self, despair)
353 Connects to the specified destination through a proxy.
354 destpar - A tuple of the IP/DNS address and the port number.
355 (identical to socket's connect).
356 To select the proxy server use setproxy().
358 # Do a minimal input check first
359 if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int):
360 raise GeneralProxyError((5, _generalerrors[5]))
361 if self.__proxy[0] == PROXY_TYPE_SOCKS5:
362 if self.__proxy[2] != None:
363 portnum = self.__proxy[2]
366 _orgsocket.connect(self, (self.__proxy[1], portnum))
367 self.__negotiatesocks5(destpair[0], destpair[1])
368 elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
369 if self.__proxy[2] != None:
370 portnum = self.__proxy[2]
373 _orgsocket.connect(self,(self.__proxy[1], portnum))
374 self.__negotiatesocks4(destpair[0], destpair[1])
375 elif self.__proxy[0] == PROXY_TYPE_HTTP:
376 if self.__proxy[2] != None:
377 portnum = self.__proxy[2]
380 _orgsocket.connect(self,(self.__proxy[1], portnum))
381 self.__negotiatehttp(destpair[0], destpair[1])
382 elif self.__proxy[0] == None:
383 _orgsocket.connect(self, (destpair[0], destpair[1]))
385 raise GeneralProxyError((4, _generalerrors[4]))