PageRenderTime 61ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/socks/__init__.py

https://gitlab.com/akila-33/Sick-Beard
Python | 393 lines | 355 code | 9 blank | 29 comment | 1 complexity | 0bc39d3f6a09e0c5182372cc9eceffbe MD5 | raw file
  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. """
  32. import re
  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. PROXY_REGEX = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*):([^/?#]*))?")
  40. _defaultproxy = None
  41. _orgsocket = socket.socket
  42. class ProxyError(Exception): pass
  43. class GeneralProxyError(ProxyError): pass
  44. class Socks5AuthError(ProxyError): pass
  45. class Socks5Error(ProxyError): pass
  46. class Socks4Error(ProxyError): pass
  47. class HTTPError(ProxyError): pass
  48. _generalerrors = ("success",
  49. "invalid data",
  50. "not connected",
  51. "not available",
  52. "bad proxy type",
  53. "bad input")
  54. _socks5errors = ("succeeded",
  55. "general SOCKS server failure",
  56. "connection not allowed by ruleset",
  57. "Network unreachable",
  58. "Host unreachable",
  59. "Connection refused",
  60. "TTL expired",
  61. "Command not supported",
  62. "Address type not supported",
  63. "Unknown error")
  64. _socks5autherrors = ("succeeded",
  65. "authentication is required",
  66. "all offered authentication methods were rejected",
  67. "unknown username or invalid password",
  68. "unknown error")
  69. _socks4errors = ("request granted",
  70. "request rejected or failed",
  71. "request rejected because SOCKS server cannot connect to identd on the client",
  72. "request rejected because the client program and identd report different user-ids",
  73. "unknown error")
  74. def parseproxyuri(proxyurl):
  75. """Parses a http proxy uri in the format x://a.b.c.d:port
  76. (protocol, addr, port) = parseproxyuri(uri)
  77. """
  78. groups = PROXY_REGEX.match(proxyurl).groups()
  79. return (groups[1], groups[3], groups[4])
  80. def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
  81. """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
  82. Sets a default proxy which all further socksocket objects will use,
  83. unless explicitly changed.
  84. """
  85. global _defaultproxy
  86. _defaultproxy = (proxytype, addr, port, rdns, username, password)
  87. def wrapmodule(module):
  88. """wrapmodule(module)
  89. Attempts to replace a module's socket library with a SOCKS socket. Must set
  90. a default proxy using setdefaultproxy(...) first.
  91. This will only work on modules that import socket directly into the namespace;
  92. most of the Python Standard Library falls into this category.
  93. """
  94. if _defaultproxy != None:
  95. module.socket.socket = socksocket
  96. else:
  97. raise GeneralProxyError((4, "no proxy specified"))
  98. class socksocket(socket.socket):
  99. """socksocket([family[, type[, proto]]]) -> socket object
  100. Open a SOCKS enabled socket. The parameters are the same as
  101. those of the standard socket init. In order for SOCKS to work,
  102. you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
  103. """
  104. def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
  105. _orgsocket.__init__(self, family, type, proto, _sock)
  106. if _defaultproxy != None:
  107. self.__proxy = _defaultproxy
  108. else:
  109. self.__proxy = (None, None, None, None, None, None)
  110. self.__proxysockname = None
  111. self.__proxypeername = None
  112. def __recvall(self, count):
  113. """__recvall(count) -> data
  114. Receive EXACTLY the number of bytes requested from the socket.
  115. Blocks until the required number of bytes have been received.
  116. """
  117. data = self.recv(count)
  118. while len(data) < count:
  119. d = self.recv(count-len(data))
  120. if not d: raise GeneralProxyError((0, "connection closed unexpectedly"))
  121. data = data + d
  122. return data
  123. def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
  124. """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
  125. Sets the proxy to be used.
  126. proxytype - The type of the proxy to be used. Three types
  127. are supported: PROXY_TYPE_SOCKS4 (including socks4a),
  128. PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
  129. addr - The address of the server (IP or DNS).
  130. port - The port of the server. Defaults to 1080 for SOCKS
  131. servers and 8080 for HTTP proxy servers.
  132. rdns - Should DNS queries be preformed on the remote side
  133. (rather than the local side). The default is True.
  134. Note: This has no effect with SOCKS4 servers.
  135. username - Username to authenticate with to the server.
  136. The default is no authentication.
  137. password - Password to authenticate with to the server.
  138. Only relevant when username is also provided.
  139. """
  140. self.__proxy = (proxytype, addr, port, rdns, username, password)
  141. def __negotiatesocks5(self, destaddr, destport):
  142. """__negotiatesocks5(self,destaddr,destport)
  143. Negotiates a connection through a SOCKS5 server.
  144. """
  145. # First we'll send the authentication packages we support.
  146. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
  147. # The username/password details were supplied to the
  148. # setproxy method so we support the USERNAME/PASSWORD
  149. # authentication (in addition to the standard none).
  150. self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02))
  151. else:
  152. # No username/password were entered, therefore we
  153. # only support connections with no authentication.
  154. self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00))
  155. # We'll receive the server's response to determine which
  156. # method was selected
  157. chosenauth = self.__recvall(2)
  158. if chosenauth[0:1] != chr(0x05).encode():
  159. self.close()
  160. raise GeneralProxyError((1, _generalerrors[1]))
  161. # Check the chosen authentication method
  162. if chosenauth[1:2] == chr(0x00).encode():
  163. # No authentication is required
  164. pass
  165. elif chosenauth[1:2] == chr(0x02).encode():
  166. # Okay, we need to perform a basic username/password
  167. # authentication.
  168. self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5])
  169. authstat = self.__recvall(2)
  170. if authstat[0:1] != chr(0x01).encode():
  171. # Bad response
  172. self.close()
  173. raise GeneralProxyError((1, _generalerrors[1]))
  174. if authstat[1:2] != chr(0x00).encode():
  175. # Authentication failed
  176. self.close()
  177. raise Socks5AuthError((3, _socks5autherrors[3]))
  178. # Authentication succeeded
  179. else:
  180. # Reaching here is always bad
  181. self.close()
  182. if chosenauth[1] == chr(0xFF).encode():
  183. raise Socks5AuthError((2, _socks5autherrors[2]))
  184. else:
  185. raise GeneralProxyError((1, _generalerrors[1]))
  186. # Now we can request the actual connection
  187. req = struct.pack('BBB', 0x05, 0x01, 0x00)
  188. # If the given destination address is an IP address, we'll
  189. # use the IPv4 address request even if remote resolving was specified.
  190. try:
  191. ipaddr = socket.inet_aton(destaddr)
  192. req = req + chr(0x01).encode() + ipaddr
  193. except socket.error:
  194. # Well it's not an IP number, so it's probably a DNS name.
  195. if self.__proxy[3]:
  196. # Resolve remotely
  197. ipaddr = None
  198. req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr
  199. else:
  200. # Resolve locally
  201. ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
  202. req = req + chr(0x01).encode() + ipaddr
  203. req = req + struct.pack(">H", destport)
  204. self.sendall(req)
  205. # Get the response
  206. resp = self.__recvall(4)
  207. if resp[0:1] != chr(0x05).encode():
  208. self.close()
  209. raise GeneralProxyError((1, _generalerrors[1]))
  210. elif resp[1:2] != chr(0x00).encode():
  211. # Connection failed
  212. self.close()
  213. if ord(resp[1:2])<=8:
  214. raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])]))
  215. else:
  216. raise Socks5Error((9, _socks5errors[9]))
  217. # Get the bound address/port
  218. elif resp[3:4] == chr(0x01).encode():
  219. boundaddr = self.__recvall(4)
  220. elif resp[3:4] == chr(0x03).encode():
  221. resp = resp + self.recv(1)
  222. boundaddr = self.__recvall(ord(resp[4:5]))
  223. else:
  224. self.close()
  225. raise GeneralProxyError((1,_generalerrors[1]))
  226. boundport = struct.unpack(">H", self.__recvall(2))[0]
  227. self.__proxysockname = (boundaddr, boundport)
  228. if ipaddr != None:
  229. self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
  230. else:
  231. self.__proxypeername = (destaddr, destport)
  232. def getproxysockname(self):
  233. """getsockname() -> address info
  234. Returns the bound IP address and port number at the proxy.
  235. """
  236. return self.__proxysockname
  237. def getproxypeername(self):
  238. """getproxypeername() -> address info
  239. Returns the IP and port number of the proxy.
  240. """
  241. return _orgsocket.getpeername(self)
  242. def getpeername(self):
  243. """getpeername() -> address info
  244. Returns the IP address and port number of the destination
  245. machine (note: getproxypeername returns the proxy)
  246. """
  247. return self.__proxypeername
  248. def __negotiatesocks4(self,destaddr,destport):
  249. """__negotiatesocks4(self,destaddr,destport)
  250. Negotiates a connection through a SOCKS4 server.
  251. """
  252. # Check if the destination address provided is an IP address
  253. rmtrslv = False
  254. try:
  255. ipaddr = socket.inet_aton(destaddr)
  256. except socket.error:
  257. # It's a DNS name. Check where it should be resolved.
  258. if self.__proxy[3]:
  259. ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01)
  260. rmtrslv = True
  261. else:
  262. ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
  263. # Construct the request packet
  264. req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
  265. # The username parameter is considered userid for SOCKS4
  266. if self.__proxy[4] != None:
  267. req = req + self.__proxy[4]
  268. req = req + chr(0x00).encode()
  269. # DNS name if remote resolving is required
  270. # NOTE: This is actually an extension to the SOCKS4 protocol
  271. # called SOCKS4A and may not be supported in all cases.
  272. if rmtrslv:
  273. req = req + destaddr + chr(0x00).encode()
  274. self.sendall(req)
  275. # Get the response from the server
  276. resp = self.__recvall(8)
  277. if resp[0:1] != chr(0x00).encode():
  278. # Bad data
  279. self.close()
  280. raise GeneralProxyError((1,_generalerrors[1]))
  281. if resp[1:2] != chr(0x5A).encode():
  282. # Server returned an error
  283. self.close()
  284. if ord(resp[1:2]) in (91, 92, 93):
  285. self.close()
  286. raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90]))
  287. else:
  288. raise Socks4Error((94, _socks4errors[4]))
  289. # Get the bound address/port
  290. self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0])
  291. if rmtrslv != None:
  292. self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
  293. else:
  294. self.__proxypeername = (destaddr, destport)
  295. def __negotiatehttp(self, destaddr, destport):
  296. """__negotiatehttp(self,destaddr,destport)
  297. Negotiates a connection through an HTTP server.
  298. """
  299. # If we need to resolve locally, we do this now
  300. if not self.__proxy[3]:
  301. addr = socket.gethostbyname(destaddr)
  302. else:
  303. addr = destaddr
  304. self.sendall(("CONNECT " + addr + ":" + str(destport) + " HTTP/1.1\r\n" + "Host: " + destaddr + "\r\n\r\n").encode())
  305. # We read the response until we get the string "\r\n\r\n"
  306. resp = self.recv(1)
  307. while resp.find("\r\n\r\n".encode()) == -1:
  308. resp = resp + self.recv(1)
  309. # We just need the first line to check if the connection
  310. # was successful
  311. statusline = resp.splitlines()[0].split(" ".encode(), 2)
  312. if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
  313. self.close()
  314. raise GeneralProxyError((1, _generalerrors[1]))
  315. try:
  316. statuscode = int(statusline[1])
  317. except ValueError:
  318. self.close()
  319. raise GeneralProxyError((1, _generalerrors[1]))
  320. if statuscode != 200:
  321. self.close()
  322. raise HTTPError((statuscode, statusline[2]))
  323. self.__proxysockname = ("0.0.0.0", 0)
  324. self.__proxypeername = (addr, destport)
  325. def connect(self, destpair):
  326. """connect(self, despair)
  327. Connects to the specified destination through a proxy.
  328. destpar - A tuple of the IP/DNS address and the port number.
  329. (identical to socket's connect).
  330. To select the proxy server use setproxy().
  331. """
  332. # Do a minimal input check first
  333. if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int):
  334. raise GeneralProxyError((5, _generalerrors[5]))
  335. if self.__proxy[0] == PROXY_TYPE_SOCKS5:
  336. if self.__proxy[2] != None:
  337. portnum = self.__proxy[2]
  338. else:
  339. portnum = 1080
  340. _orgsocket.connect(self, (self.__proxy[1], portnum))
  341. self.__negotiatesocks5(destpair[0], destpair[1])
  342. elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
  343. if self.__proxy[2] != None:
  344. portnum = self.__proxy[2]
  345. else:
  346. portnum = 1080
  347. _orgsocket.connect(self,(self.__proxy[1], portnum))
  348. self.__negotiatesocks4(destpair[0], destpair[1])
  349. elif self.__proxy[0] == PROXY_TYPE_HTTP:
  350. if self.__proxy[2] != None:
  351. portnum = self.__proxy[2]
  352. else:
  353. portnum = 8080
  354. _orgsocket.connect(self,(self.__proxy[1], portnum))
  355. self.__negotiatehttp(destpair[0], destpair[1])
  356. elif self.__proxy[0] == None:
  357. _orgsocket.connect(self, (destpair[0], destpair[1]))
  358. else:
  359. raise GeneralProxyError((4, _generalerrors[4]))