Guest User

Untitled

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