Advertisement
MOVZX

Socks.py

Dec 25th, 2014
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Cloned from: http://pastebin.com/ahkPbvKA
  2.  
  3. import socket
  4. import struct
  5.  
  6. PROXY_TYPE_SOCKS4 = 1
  7. PROXY_TYPE_SOCKS5 = 2
  8. PROXY_TYPE_HTTP = 3
  9.  
  10. _defaultproxy = None
  11. _orgsocket = socket.socket
  12.  
  13. class ProxyError(Exception):
  14.     def __init__(self, value):
  15.         self.value = value
  16.     def __str__(self):
  17.         return repr(self.value)
  18.  
  19. class GeneralProxyError(ProxyError):
  20.     def __init__(self, value):
  21.         self.value = value
  22.     def __str__(self):
  23.         return repr(self.value)
  24.  
  25. class Socks5AuthError(ProxyError):
  26.     def __init__(self, value):
  27.         self.value = value
  28.     def __str__(self):
  29.         return repr(self.value)
  30.  
  31. class Socks5Error(ProxyError):
  32.     def __init__(self, value):
  33.         self.value = value
  34.     def __str__(self):
  35.         return repr(self.value)
  36.  
  37. class Socks4Error(ProxyError):
  38.     def __init__(self, value):
  39.         self.value = value
  40.     def __str__(self):
  41.         return repr(self.value)
  42.  
  43. class HTTPError(ProxyError):
  44.     def __init__(self, value):
  45.         self.value = value
  46.     def __str__(self):
  47.         return repr(self.value)
  48.  
  49. _generalerrors = ("success",
  50.            "invalid data",
  51.            "not connected",
  52.            "not available",
  53.            "bad proxy type",
  54.            "bad input")
  55.  
  56. _socks5errors = ("succeeded",
  57.           "general SOCKS server failure",
  58.           "connection not allowed by ruleset",
  59.           "Network unreachable",
  60.           "Host unreachable",
  61.           "Connection refused",
  62.           "TTL expired",
  63.           "Command not supported",
  64.           "Address type not supported",
  65.           "Unknown error")
  66.  
  67. _socks5autherrors = ("succeeded",
  68.               "authentication is required",
  69.               "all offered authentication methods were rejected",
  70.               "unknown username or invalid password",
  71.               "unknown error")
  72.  
  73. _socks4errors = ("request granted",
  74.           "request rejected or failed",
  75.           "request rejected because SOCKS server cannot connect to identd on the client",
  76.           "request rejected because the client program and identd report different user-ids",
  77.           "unknown error")
  78.  
  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.    
  87. class socksocket(socket.socket):
  88.     """socksocket([family[, type[, proto]]]) -> socket object
  89.    
  90.     Open a SOCKS enabled socket. The parameters are the same as
  91.     those of the standard socket init. In order for SOCKS to work,
  92.     you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
  93.     """
  94.    
  95.     def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
  96.         _orgsocket.__init__(self,family,type,proto,_sock)
  97.         if _defaultproxy != None:
  98.             self.__proxy = _defaultproxy
  99.         else:
  100.             self.__proxy = (None, None, None, None, None, None)
  101.         self.__proxysockname = None
  102.         self.__proxypeername = None
  103.    
  104.     def __recvall(self, bytes):
  105.         """__recvall(bytes) -> data
  106.         Receive EXACTLY the number of bytes requested from the socket.
  107.         Blocks until the required number of bytes have been received.
  108.         """
  109.         data = ""
  110.         while len(data) < bytes:
  111.             data = data + self.recv(bytes-len(data))
  112.         return data
  113.    
  114.     def setproxy(self,proxytype=None,addr=None,port=None,rdns=True,username=None,password=None):
  115.         """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
  116.         Sets the proxy to be used.
  117.         proxytype - The type of the proxy to be used. Three types
  118.                 are supported: PROXY_TYPE_SOCKS4 (including socks4a),
  119.                 PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
  120.         addr -      The address of the server (IP or DNS).
  121.         port -      The port of the server. Defaults to 1080 for SOCKS
  122.                 servers and 8080 for HTTP proxy servers.
  123.         rdns -      Should DNS queries be preformed on the remote side
  124.                 (rather than the local side). The default is True.
  125.                 Note: This has no effect with SOCKS4 servers.
  126.         username -  Username to authenticate with to the server.
  127.                 The default is no authentication.
  128.         password -  Password to authenticate with to the server.
  129.                 Only relevant when username is also provided.
  130.         """
  131.         self.__proxy = (proxytype,addr,port,rdns,username,password)
  132.    
  133.     def __negotiatesocks5(self,destaddr,destport):
  134.         """__negotiatesocks5(self,destaddr,destport)
  135.         Negotiates a connection through a SOCKS5 server.
  136.         """
  137.         # First we'll send the authentication packages we support.
  138.         if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
  139.             # The username/password details were supplied to the
  140.             # setproxy method so we support the USERNAME/PASSWORD
  141.             # authentication (in addition to the standard none).
  142.             self.sendall("\x05\x02\x00\x02")
  143.         else:
  144.             # No username/password were entered, therefore we
  145.             # only support connections with no authentication.
  146.             self.sendall("\x05\x01\x00")
  147.         # We'll receive the server's response to determine which
  148.         # method was selected
  149.         chosenauth = self.__recvall(2)
  150.         if chosenauth[0] != "\x05":
  151.             self.close()
  152.             raise GeneralProxyError((1,_generalerrors[1]))
  153.         # Check the chosen authentication method
  154.         if chosenauth[1] == "\x00":
  155.             # No authentication is required
  156.             pass
  157.         elif chosenauth[1] == "\x02":
  158.             # Okay, we need to perform a basic username/password
  159.             # authentication.
  160.             self.sendall("\x01" + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.proxy[5])) + self.__proxy[5])
  161.             authstat = self.__recvall(2)
  162.             if authstat[0] != "\x01":
  163.                 # Bad response
  164.                 self.close()
  165.                 raise GeneralProxyError((1,_generalerrors[1]))
  166.             if authstat[1] != "\x00":
  167.                 # Authentication failed
  168.                 self.close()
  169.                 raise Socks5AuthError,((3,_socks5autherrors[3]))
  170.             # Authentication succeeded
  171.         else:
  172.             # Reaching here is always bad
  173.             self.close()
  174.             if chosenauth[1] == "\xFF":
  175.                 raise Socks5AuthError((2,_socks5autherrors[2]))
  176.             else:
  177.                 raise GeneralProxyError((1,_generalerrors[1]))
  178.         # Now we can request the actual connection
  179.         req = "\x05\x01\x00"
  180.         # If the given destination address is an IP address, we'll
  181.         # use the IPv4 address request even if remote resolving was specified.
  182.         try:
  183.             ipaddr = socket.inet_aton(destaddr)
  184.             req = req + "\x01" + ipaddr
  185.         except socket.error:
  186.             # Well it's not an IP number,  so it's probably a DNS name.
  187.             if self.__proxy[3]==True:
  188.                 # Resolve remotely
  189.                 ipaddr = None
  190.                 req = req + "\x03" + chr(len(destaddr)) + destaddr
  191.             else:
  192.                 # Resolve locally
  193.                 ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
  194.                 req = req + "\x01" + ipaddr
  195.         req = req + struct.pack(">H",destport)
  196.         self.sendall(req)
  197.         # Get the response
  198.         resp = self.__recvall(4)
  199.         if resp[0] != "\x05":
  200.             self.close()
  201.             raise GeneralProxyError((1,_generalerrors[1]))
  202.         elif resp[1] != "\x00":
  203.             # Connection failed
  204.             self.close()
  205.             if ord(resp[1])<=8:
  206.                 raise Socks5Error(ord(resp[1]),_generalerrors[ord(resp[1])])
  207.             else:
  208.                 raise Socks5Error(9,_generalerrors[9])
  209.         # Get the bound address/port
  210.         elif resp[3] == "\x01":
  211.             boundaddr = self.__recvall(4)
  212.         elif resp[3] == "\x03":
  213.             resp = resp + self.recv(1)
  214.             boundaddr = self.__recvall(resp[4])
  215.         else:
  216.             self.close()
  217.             raise GeneralProxyError((1,_generalerrors[1]))
  218.         boundport = struct.unpack(">H",self.__recvall(2))[0]
  219.         self.__proxysockname = (boundaddr,boundport)
  220.         if ipaddr != None:
  221.             self.__proxypeername = (socket.inet_ntoa(ipaddr),destport)
  222.         else:
  223.             self.__proxypeername = (destaddr,destport)
  224.    
  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.    
  231.     def getproxypeername(self):
  232.         """getproxypeername() -> address info
  233.         Returns the IP and port number of the proxy.
  234.         """
  235.         return _orgsocket.getpeername(self)
  236.    
  237.     def getpeername(self):
  238.         """getpeername() -> address info
  239.         Returns the IP address and port number of the destination
  240.         machine (note: getproxypeername returns the proxy)
  241.         """
  242.         return self.__proxypeername
  243.    
  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.    
  292.     def __negotiatehttp(self,destaddr,destport):
  293.         """__negotiatehttp(self,destaddr,destport)
  294.         Negotiates a connection through an HTTP server.
  295.         """
  296.         # If we need to resolve locally, we do this now
  297.         if self.__proxy[3] == False:
  298.             addr = socket.gethostbyname(destaddr)
  299.         else:
  300.             addr = destaddr
  301.         self.sendall("CONNECT " + addr + ":" + str(destport) + " HTTP/1.1\r\n" + "Host: " + destaddr + "\r\n\r\n")
  302.         # We read the response until we get the string "\r\n\r\n"
  303.         resp = self.recv(1)
  304.         while resp.find("\r\n\r\n")==-1:
  305.             resp = resp + self.recv(1)
  306.         # We just need the first line to check if the connection
  307.         # was successful
  308.         statusline = resp.splitlines()[0].split(" ",2)
  309.         if statusline[0] not in ("HTTP/1.0","HTTP/1.1"):
  310.             self.close()
  311.             raise GeneralProxyError((1,_generalerrors[1]))
  312.         try:
  313.             statuscode = int(statusline[1])
  314.         except ValueError:
  315.             self.close()
  316.             raise GeneralProxyError((1,_generalerrors[1]))
  317.         if statuscode != 200:
  318.             self.close()
  319.             raise HTTPError((statuscode,statusline[2]))
  320.         self.__proxysockname = ("0.0.0.0",0)
  321.         self.__proxypeername = (addr,destport)
  322.    
  323.     def connect(self,destpair):
  324.         """connect(self,despair)
  325.         Connects to the specified destination through a proxy.
  326.         destpar - A tuple of the IP/DNS address and the port number.
  327.         (identical to socket's connect).
  328.         To select the proxy server use setproxy().
  329.         """
  330.         # Do a minimal input check first
  331.         if (type(destpair) in (list,tuple)==False) or (len(destpair)<2) or (type(destpair[0])!=str) or (type(destpair[1])!=int):
  332.             raise GeneralProxyError((5,_generalerrors[5]))
  333.         if self.__proxy[0] == PROXY_TYPE_SOCKS5:
  334.             if self.__proxy[2] != None:
  335.                 portnum = self.__proxy[2]
  336.             else:
  337.                 portnum = 1080
  338.             _orgsocket.connect(self,(self.__proxy[1],portnum))
  339.             self.__negotiatesocks5(destpair[0],destpair[1])
  340.         elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
  341.             if self.__proxy[2] != None:
  342.                 portnum = self.__proxy[2]
  343.             else:
  344.                 portnum = 1080
  345.             _orgsocket.connect(self,(self.__proxy[1],portnum))
  346.             self.__negotiatesocks4(destpair[0],destpair[1])
  347.         elif self.__proxy[0] == PROXY_TYPE_HTTP:
  348.             if self.__proxy[2] != None:
  349.                 portnum = self.__proxy[2]
  350.             else:
  351.                 portnum = 8080
  352.             _orgsocket.connect(self,(self.__proxy[1],portnum))
  353.             self.__negotiatehttp(destpair[0],destpair[1])
  354.         elif self.__proxy[0] == None:
  355.             _orgsocket.connect(self,(destpair[0],destpair[1]))
  356.         else:
  357.             raise GeneralProxyError((4,_generalerrors[4]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement