socks.py 16 KB

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