PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/socks/__init__.py

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