socks.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-"
  3. # vim: set expandtab tabstop=4 shiftwidth=4:
  4. """SocksiPy - Python SOCKS module.
  5. Version 1.00
  6. Copyright 2006 Dan-Haim. All rights reserved.
  7. Redistribution and use in source and binary forms, with or without modification,
  8. are permitted provided that the following conditions are met:
  9. 1. Redistributions of source code must retain the above copyright notice, this
  10. list of conditions and the following disclaimer.
  11. 2. Redistributions in binary form must reproduce the above copyright notice,
  12. this list of conditions and the following disclaimer in the documentation
  13. and/or other materials provided with the distribution.
  14. 3. Neither the name of Dan Haim nor the names of his contributors may be used
  15. to endorse or promote products derived from this software without specific
  16. 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.
  26. This module provides a standard socket-like interface for Python
  27. for tunneling connections through SOCKS proxies.
  28. """
  29. """
  30. Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
  31. for use in PyLoris (http://pyloris.sourceforge.net/)
  32. Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
  33. mainly to merge bug fixes found in Sourceforge
  34. """
  35. import base64
  36. import socket
  37. import struct
  38. import sys
  39. if getattr(socket, 'socket', None) is None:
  40. raise ImportError('socket.socket missing, proxy support unusable')
  41. PROXY_TYPE_SOCKS4 = 1
  42. PROXY_TYPE_SOCKS5 = 2
  43. PROXY_TYPE_HTTP = 3
  44. PROXY_TYPE_HTTP_NO_TUNNEL = 4
  45. _defaultproxy = None
  46. _orgsocket = socket.socket
  47. class ProxyError(Exception): pass
  48. class GeneralProxyError(ProxyError): pass
  49. class Socks5AuthError(ProxyError): pass
  50. class Socks5Error(ProxyError): pass
  51. class Socks4Error(ProxyError): pass
  52. class HTTPError(ProxyError): pass
  53. _generalerrors = ("success",
  54. "invalid data",
  55. "not connected",
  56. "not available",
  57. "bad proxy type",
  58. "bad input")
  59. _socks5errors = ("succeeded",
  60. "general SOCKS server failure",
  61. "connection not allowed by ruleset",
  62. "Network unreachable",
  63. "Host unreachable",
  64. "Connection refused",
  65. "TTL expired",
  66. "Command not supported",
  67. "Address type not supported",
  68. "Unknown error")
  69. _socks5autherrors = ("succeeded",
  70. "authentication is required",
  71. "all offered authentication methods were rejected",
  72. "unknown username or invalid password",
  73. "unknown error")
  74. _socks4errors = ("request granted",
  75. "request rejected or failed",
  76. "request rejected because SOCKS server cannot connect to identd on the client",
  77. "request rejected because the client program and identd report different user-ids",
  78. "unknown error")
  79. def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
  80. """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
  81. Sets a default proxy which all further socksocket objects will use,
  82. unless explicitly changed.
  83. """
  84. global _defaultproxy
  85. _defaultproxy = (proxytype, addr, port, rdns, username, password)
  86. def wrapmodule(module):
  87. """wrapmodule(module)
  88. Attempts to replace a module's socket library with a SOCKS socket. Must set
  89. a default proxy using setdefaultproxy(...) first.
  90. This will only work on modules that import socket directly into the namespace;
  91. most of the Python Standard Library falls into this category.
  92. """
  93. if _defaultproxy != None:
  94. module.socket.socket = socksocket
  95. else:
  96. raise GeneralProxyError((4, "no proxy specified"))
  97. class socksocket(socket.socket):
  98. """socksocket([family[, type[, proto]]]) -> socket object
  99. Open a SOCKS enabled socket. The parameters are the same as
  100. those of the standard socket init. In order for SOCKS to work,
  101. you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
  102. """
  103. def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
  104. _orgsocket.__init__(self, family, type, proto, _sock)
  105. if _defaultproxy != None:
  106. self.__proxy = _defaultproxy
  107. else:
  108. self.__proxy = (None, None, None, None, None, None)
  109. self.__proxysockname = None
  110. self.__proxypeername = None
  111. self.__httptunnel = True
  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 sendall(self, content, *args):
  124. """ override socket.socket.sendall method to rewrite the header
  125. for non-tunneling proxies if needed
  126. """
  127. if not self.__httptunnel:
  128. content = self.__rewriteproxy(content)
  129. return super(socksocket, self).sendall(content, *args)
  130. def __rewriteproxy(self, header):
  131. """ rewrite HTTP request headers to support non-tunneling proxies
  132. (i.e. those which do not support the CONNECT method).
  133. This only works for HTTP (not HTTPS) since HTTPS requires tunneling.
  134. """
  135. host, endpt = None, None
  136. hdrs = header.split("\r\n")
  137. for hdr in hdrs:
  138. if hdr.lower().startswith("host:"):
  139. host = hdr
  140. elif hdr.lower().startswith("get") or hdr.lower().startswith("post"):
  141. endpt = hdr
  142. if host and endpt:
  143. hdrs.remove(host)
  144. hdrs.remove(endpt)
  145. host = host.split(" ")[1]
  146. endpt = endpt.split(" ")
  147. if (self.__proxy[4] != None and self.__proxy[5] != None):
  148. hdrs.insert(0, self.__getauthheader())
  149. hdrs.insert(0, "Host: %s" % host)
  150. hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2]))
  151. return "\r\n".join(hdrs)
  152. def __getauthheader(self):
  153. auth = self.__proxy[4] + ":" + self.__proxy[5]
  154. return "Proxy-Authorization: Basic " + base64.b64encode(auth)
  155. def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
  156. """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
  157. Sets the proxy to be used.
  158. proxytype - The type of the proxy to be used. Three types
  159. are supported: PROXY_TYPE_SOCKS4 (including socks4a),
  160. PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
  161. addr - The address of the server (IP or DNS).
  162. port - The port of the server. Defaults to 1080 for SOCKS
  163. servers and 8080 for HTTP proxy servers.
  164. rdns - Should DNS queries be preformed on the remote side
  165. (rather than the local side). The default is True.
  166. Note: This has no effect with SOCKS4 servers.
  167. username - Username to authenticate with to the server.
  168. The default is no authentication.
  169. password - Password to authenticate with to the server.
  170. Only relevant when username is also provided.
  171. """
  172. self.__proxy = (proxytype, addr, port, rdns, username, password)
  173. def __negotiatesocks5(self, destaddr, destport):
  174. """__negotiatesocks5(self,destaddr,destport)
  175. Negotiates a connection through a SOCKS5 server.
  176. """
  177. # First we'll send the authentication packages we support.
  178. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
  179. # The username/password details were supplied to the
  180. # setproxy method so we support the USERNAME/PASSWORD
  181. # authentication (in addition to the standard none).
  182. self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02))
  183. else:
  184. # No username/password were entered, therefore we
  185. # only support connections with no authentication.
  186. self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00))
  187. # We'll receive the server's response to determine which
  188. # method was selected
  189. chosenauth = self.__recvall(2)
  190. if chosenauth[0:1] != chr(0x05).encode():
  191. self.close()
  192. raise GeneralProxyError((1, _generalerrors[1]))
  193. # Check the chosen authentication method
  194. if chosenauth[1:2] == chr(0x00).encode():
  195. # No authentication is required
  196. pass
  197. elif chosenauth[1:2] == chr(0x02).encode():
  198. # Okay, we need to perform a basic username/password
  199. # authentication.
  200. self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5])
  201. authstat = self.__recvall(2)
  202. if authstat[0:1] != chr(0x01).encode():
  203. # Bad response
  204. self.close()
  205. raise GeneralProxyError((1, _generalerrors[1]))
  206. if authstat[1:2] != chr(0x00).encode():
  207. # Authentication failed
  208. self.close()
  209. raise Socks5AuthError((3, _socks5autherrors[3]))
  210. # Authentication succeeded
  211. else:
  212. # Reaching here is always bad
  213. self.close()
  214. if chosenauth[1] == chr(0xFF).encode():
  215. raise Socks5AuthError((2, _socks5autherrors[2]))
  216. else:
  217. raise GeneralProxyError((1, _generalerrors[1]))
  218. # Now we can request the actual connection
  219. req = struct.pack('BBB', 0x05, 0x01, 0x00)
  220. # If the given destination address is an IP address, we'll
  221. # use the IPv4 address request even if remote resolving was specified.
  222. try:
  223. ipaddr = socket.inet_aton(destaddr)
  224. req = req + chr(0x01).encode() + ipaddr
  225. except socket.error:
  226. # Well it's not an IP number, so it's probably a DNS name.
  227. if self.__proxy[3]:
  228. # Resolve remotely
  229. ipaddr = None
  230. req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr
  231. else:
  232. # Resolve locally
  233. ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
  234. req = req + chr(0x01).encode() + ipaddr
  235. req = req + struct.pack(">H", destport)
  236. self.sendall(req)
  237. # Get the response
  238. resp = self.__recvall(4)
  239. if resp[0:1] != chr(0x05).encode():
  240. self.close()
  241. raise GeneralProxyError((1, _generalerrors[1]))
  242. elif resp[1:2] != chr(0x00).encode():
  243. # Connection failed
  244. self.close()
  245. if ord(resp[1:2])<=8:
  246. raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])]))
  247. else:
  248. raise Socks5Error((9, _socks5errors[9]))
  249. # Get the bound address/port
  250. elif resp[3:4] == chr(0x01).encode():
  251. boundaddr = self.__recvall(4)
  252. elif resp[3:4] == chr(0x03).encode():
  253. resp = resp + self.recv(1)
  254. boundaddr = self.__recvall(ord(resp[4:5]))
  255. else:
  256. self.close()
  257. raise GeneralProxyError((1,_generalerrors[1]))
  258. boundport = struct.unpack(">H", self.__recvall(2))[0]
  259. self.__proxysockname = (boundaddr, boundport)
  260. if ipaddr != None:
  261. self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
  262. else:
  263. self.__proxypeername = (destaddr, destport)
  264. def getproxysockname(self):
  265. """getsockname() -> address info
  266. Returns the bound IP address and port number at the proxy.
  267. """
  268. return self.__proxysockname
  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. def getpeername(self):
  275. """getpeername() -> address info
  276. Returns the IP address and port number of the destination
  277. machine (note: getproxypeername returns the proxy)
  278. """
  279. return self.__proxypeername
  280. def __negotiatesocks4(self,destaddr,destport):
  281. """__negotiatesocks4(self,destaddr,destport)
  282. Negotiates a connection through a SOCKS4 server.
  283. """
  284. # Check if the destination address provided is an IP address
  285. rmtrslv = False
  286. try:
  287. ipaddr = socket.inet_aton(destaddr)
  288. except socket.error:
  289. # It's a DNS name. Check where it should be resolved.
  290. if self.__proxy[3]:
  291. ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01)
  292. rmtrslv = True
  293. else:
  294. ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
  295. # Construct the request packet
  296. req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
  297. # The username parameter is considered userid for SOCKS4
  298. if self.__proxy[4] != None:
  299. req = req + self.__proxy[4]
  300. req = req + chr(0x00).encode()
  301. # DNS name if remote resolving is required
  302. # NOTE: This is actually an extension to the SOCKS4 protocol
  303. # called SOCKS4A and may not be supported in all cases.
  304. if rmtrslv:
  305. req = req + destaddr + chr(0x00).encode()
  306. self.sendall(req)
  307. # Get the response from the server
  308. resp = self.__recvall(8)
  309. if resp[0:1] != chr(0x00).encode():
  310. # Bad data
  311. self.close()
  312. raise GeneralProxyError((1,_generalerrors[1]))
  313. if resp[1:2] != chr(0x5A).encode():
  314. # Server returned an error
  315. self.close()
  316. if ord(resp[1:2]) in (91, 92, 93):
  317. self.close()
  318. raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90]))
  319. else:
  320. raise Socks4Error((94, _socks4errors[4]))
  321. # Get the bound address/port
  322. self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0])
  323. if rmtrslv != None:
  324. self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
  325. else:
  326. self.__proxypeername = (destaddr, destport)
  327. def __negotiatehttp(self, destaddr, destport):
  328. """__negotiatehttp(self,destaddr,destport)
  329. Negotiates a connection through an HTTP server.
  330. """
  331. # If we need to resolve locally, we do this now
  332. if not self.__proxy[3]:
  333. addr = socket.gethostbyname(destaddr)
  334. else:
  335. addr = destaddr
  336. headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"]
  337. headers += ["Host: ", destaddr, "\r\n"]
  338. if (self.__proxy[4] != None and self.__proxy[5] != None):
  339. headers += [self.__getauthheader(), "\r\n"]
  340. headers.append("\r\n")
  341. self.sendall("".join(headers).encode())
  342. # We read the response until we get the string "\r\n\r\n"
  343. resp = self.recv(1)
  344. while resp.find("\r\n\r\n".encode()) == -1:
  345. resp = resp + self.recv(1)
  346. # We just need the first line to check if the connection
  347. # was successful
  348. statusline = resp.splitlines()[0].split(" ".encode(), 2)
  349. if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
  350. self.close()
  351. raise GeneralProxyError((1, _generalerrors[1]))
  352. try:
  353. statuscode = int(statusline[1])
  354. except ValueError:
  355. self.close()
  356. raise GeneralProxyError((1, _generalerrors[1]))
  357. if statuscode != 200:
  358. self.close()
  359. raise HTTPError((statuscode, statusline[2]))
  360. self.__proxysockname = ("0.0.0.0", 0)
  361. self.__proxypeername = (addr, destport)
  362. def connect(self, destpair):
  363. """connect(self, despair)
  364. Connects to the specified destination through a proxy.
  365. destpar - A tuple of the IP/DNS address and the port number.
  366. (identical to socket's connect).
  367. To select the proxy server use setproxy().
  368. """
  369. # Do a minimal input check first
  370. if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (not isinstance(destpair[0], basestring)) or (type(destpair[1]) != int):
  371. raise GeneralProxyError((5, _generalerrors[5]))
  372. if self.__proxy[0] == PROXY_TYPE_SOCKS5:
  373. if self.__proxy[2] != None:
  374. portnum = self.__proxy[2]
  375. else:
  376. portnum = 1080
  377. _orgsocket.connect(self, (self.__proxy[1], portnum))
  378. self.__negotiatesocks5(destpair[0], destpair[1])
  379. elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
  380. if self.__proxy[2] != None:
  381. portnum = self.__proxy[2]
  382. else:
  383. portnum = 1080
  384. _orgsocket.connect(self,(self.__proxy[1], portnum))
  385. self.__negotiatesocks4(destpair[0], destpair[1])
  386. elif self.__proxy[0] == PROXY_TYPE_HTTP:
  387. if self.__proxy[2] != None:
  388. portnum = self.__proxy[2]
  389. else:
  390. portnum = 8080
  391. _orgsocket.connect(self,(self.__proxy[1], portnum))
  392. self.__negotiatehttp(destpair[0], destpair[1])
  393. elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL:
  394. if self.__proxy[2] != None:
  395. portnum = self.__proxy[2]
  396. else:
  397. portnum = 8080
  398. _orgsocket.connect(self,(self.__proxy[1],portnum))
  399. if destpair[1] == 443:
  400. self.__negotiatehttp(destpair[0],destpair[1])
  401. else:
  402. self.__httptunnel = False
  403. elif self.__proxy[0] == None:
  404. _orgsocket.connect(self, (destpair[0], destpair[1]))
  405. else:
  406. raise GeneralProxyError((4, _generalerrors[4]))