socks.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. # Public Domain SOCKS proxy protocol implementation
  2. # Adapted from https://gist.github.com/bluec0re/cafd3764412967417fd3
  3. from __future__ import unicode_literals
  4. # References:
  5. # SOCKS4 protocol http://www.openssh.com/txt/socks4.protocol
  6. # SOCKS4A protocol http://www.openssh.com/txt/socks4a.protocol
  7. # SOCKS5 protocol https://tools.ietf.org/html/rfc1928
  8. # SOCKS5 username/password authentication https://tools.ietf.org/html/rfc1929
  9. import collections
  10. import socket
  11. from .compat import (
  12. compat_ord,
  13. compat_struct_pack,
  14. compat_struct_unpack,
  15. )
  16. __author__ = 'Timo Schmid <coding@timoschmid.de>'
  17. SOCKS4_VERSION = 4
  18. SOCKS4_REPLY_VERSION = 0x00
  19. # Excerpt from SOCKS4A protocol:
  20. # if the client cannot resolve the destination host's domain name to find its
  21. # IP address, it should set the first three bytes of DSTIP to NULL and the last
  22. # byte to a non-zero value.
  23. SOCKS4_DEFAULT_DSTIP = compat_struct_pack('!BBBB', 0, 0, 0, 0xFF)
  24. SOCKS5_VERSION = 5
  25. SOCKS5_USER_AUTH_VERSION = 0x01
  26. SOCKS5_USER_AUTH_SUCCESS = 0x00
  27. class Socks4Command(object):
  28. CMD_CONNECT = 0x01
  29. CMD_BIND = 0x02
  30. class Socks5Command(Socks4Command):
  31. CMD_UDP_ASSOCIATE = 0x03
  32. class Socks5Auth(object):
  33. AUTH_NONE = 0x00
  34. AUTH_GSSAPI = 0x01
  35. AUTH_USER_PASS = 0x02
  36. AUTH_NO_ACCEPTABLE = 0xFF # For server response
  37. class Socks5AddressType(object):
  38. ATYP_IPV4 = 0x01
  39. ATYP_DOMAINNAME = 0x03
  40. ATYP_IPV6 = 0x04
  41. class ProxyError(socket.error):
  42. ERR_SUCCESS = 0x00
  43. def __init__(self, code=None, msg=None):
  44. if code is not None and msg is None:
  45. msg = self.CODES.get(code) or 'unknown error'
  46. super(ProxyError, self).__init__(code, msg)
  47. class InvalidVersionError(ProxyError):
  48. def __init__(self, expected_version, got_version):
  49. msg = ('Invalid response version from server. Expected {0:02x} got '
  50. '{1:02x}'.format(expected_version, got_version))
  51. super(InvalidVersionError, self).__init__(0, msg)
  52. class Socks4Error(ProxyError):
  53. ERR_SUCCESS = 90
  54. CODES = {
  55. 91: 'request rejected or failed',
  56. 92: 'request rejected because SOCKS server cannot connect to identd on the client',
  57. 93: 'request rejected because the client program and identd report different user-ids'
  58. }
  59. class Socks5Error(ProxyError):
  60. ERR_GENERAL_FAILURE = 0x01
  61. CODES = {
  62. 0x01: 'general SOCKS server failure',
  63. 0x02: 'connection not allowed by ruleset',
  64. 0x03: 'Network unreachable',
  65. 0x04: 'Host unreachable',
  66. 0x05: 'Connection refused',
  67. 0x06: 'TTL expired',
  68. 0x07: 'Command not supported',
  69. 0x08: 'Address type not supported',
  70. 0xFE: 'unknown username or invalid password',
  71. 0xFF: 'all offered authentication methods were rejected'
  72. }
  73. class ProxyType(object):
  74. SOCKS4 = 0
  75. SOCKS4A = 1
  76. SOCKS5 = 2
  77. Proxy = collections.namedtuple('Proxy', (
  78. 'type', 'host', 'port', 'username', 'password', 'remote_dns'))
  79. class sockssocket(socket.socket):
  80. def __init__(self, *args, **kwargs):
  81. self._proxy = None
  82. super(sockssocket, self).__init__(*args, **kwargs)
  83. def setproxy(self, proxytype, addr, port, rdns=True, username=None, password=None):
  84. assert proxytype in (ProxyType.SOCKS4, ProxyType.SOCKS4A, ProxyType.SOCKS5)
  85. self._proxy = Proxy(proxytype, addr, port, username, password, rdns)
  86. def recvall(self, cnt):
  87. data = b''
  88. while len(data) < cnt:
  89. cur = self.recv(cnt - len(data))
  90. if not cur:
  91. raise EOFError('{0} bytes missing'.format(cnt - len(data)))
  92. data += cur
  93. return data
  94. def _recv_bytes(self, cnt):
  95. data = self.recvall(cnt)
  96. return compat_struct_unpack('!{0}B'.format(cnt), data)
  97. @staticmethod
  98. def _len_and_data(data):
  99. return compat_struct_pack('!B', len(data)) + data
  100. def _check_response_version(self, expected_version, got_version):
  101. if got_version != expected_version:
  102. self.close()
  103. raise InvalidVersionError(expected_version, got_version)
  104. def _resolve_address(self, destaddr, default, use_remote_dns):
  105. try:
  106. return socket.inet_aton(destaddr)
  107. except socket.error:
  108. if use_remote_dns and self._proxy.remote_dns:
  109. return default
  110. else:
  111. return socket.inet_aton(socket.gethostbyname(destaddr))
  112. def _setup_socks4(self, address, is_4a=False):
  113. destaddr, port = address
  114. ipaddr = self._resolve_address(destaddr, SOCKS4_DEFAULT_DSTIP, use_remote_dns=is_4a)
  115. packet = compat_struct_pack('!BBH', SOCKS4_VERSION, Socks4Command.CMD_CONNECT, port) + ipaddr
  116. username = (self._proxy.username or '').encode('utf-8')
  117. packet += username + b'\x00'
  118. if is_4a and self._proxy.remote_dns:
  119. packet += destaddr.encode('utf-8') + b'\x00'
  120. self.sendall(packet)
  121. version, resp_code, dstport, dsthost = compat_struct_unpack('!BBHI', self.recvall(8))
  122. self._check_response_version(SOCKS4_REPLY_VERSION, version)
  123. if resp_code != Socks4Error.ERR_SUCCESS:
  124. self.close()
  125. raise Socks4Error(resp_code)
  126. return (dsthost, dstport)
  127. def _setup_socks4a(self, address):
  128. self._setup_socks4(address, is_4a=True)
  129. def _socks5_auth(self):
  130. packet = compat_struct_pack('!B', SOCKS5_VERSION)
  131. auth_methods = [Socks5Auth.AUTH_NONE]
  132. if self._proxy.username and self._proxy.password:
  133. auth_methods.append(Socks5Auth.AUTH_USER_PASS)
  134. packet += compat_struct_pack('!B', len(auth_methods))
  135. packet += compat_struct_pack('!{0}B'.format(len(auth_methods)), *auth_methods)
  136. self.sendall(packet)
  137. version, method = self._recv_bytes(2)
  138. self._check_response_version(SOCKS5_VERSION, version)
  139. if method == Socks5Auth.AUTH_NO_ACCEPTABLE or (
  140. method == Socks5Auth.AUTH_USER_PASS and (not self._proxy.username or not self._proxy.password)):
  141. self.close()
  142. raise Socks5Error(Socks5Auth.AUTH_NO_ACCEPTABLE)
  143. if method == Socks5Auth.AUTH_USER_PASS:
  144. username = self._proxy.username.encode('utf-8')
  145. password = self._proxy.password.encode('utf-8')
  146. packet = compat_struct_pack('!B', SOCKS5_USER_AUTH_VERSION)
  147. packet += self._len_and_data(username) + self._len_and_data(password)
  148. self.sendall(packet)
  149. version, status = self._recv_bytes(2)
  150. self._check_response_version(SOCKS5_USER_AUTH_VERSION, version)
  151. if status != SOCKS5_USER_AUTH_SUCCESS:
  152. self.close()
  153. raise Socks5Error(Socks5Error.ERR_GENERAL_FAILURE)
  154. def _setup_socks5(self, address):
  155. destaddr, port = address
  156. ipaddr = self._resolve_address(destaddr, None, use_remote_dns=True)
  157. self._socks5_auth()
  158. reserved = 0
  159. packet = compat_struct_pack('!BBB', SOCKS5_VERSION, Socks5Command.CMD_CONNECT, reserved)
  160. if ipaddr is None:
  161. destaddr = destaddr.encode('utf-8')
  162. packet += compat_struct_pack('!B', Socks5AddressType.ATYP_DOMAINNAME)
  163. packet += self._len_and_data(destaddr)
  164. else:
  165. packet += compat_struct_pack('!B', Socks5AddressType.ATYP_IPV4) + ipaddr
  166. packet += compat_struct_pack('!H', port)
  167. self.sendall(packet)
  168. version, status, reserved, atype = self._recv_bytes(4)
  169. self._check_response_version(SOCKS5_VERSION, version)
  170. if status != Socks5Error.ERR_SUCCESS:
  171. self.close()
  172. raise Socks5Error(status)
  173. if atype == Socks5AddressType.ATYP_IPV4:
  174. destaddr = self.recvall(4)
  175. elif atype == Socks5AddressType.ATYP_DOMAINNAME:
  176. alen = compat_ord(self.recv(1))
  177. destaddr = self.recvall(alen)
  178. elif atype == Socks5AddressType.ATYP_IPV6:
  179. destaddr = self.recvall(16)
  180. destport = compat_struct_unpack('!H', self.recvall(2))[0]
  181. return (destaddr, destport)
  182. def _make_proxy(self, connect_func, address):
  183. if not self._proxy:
  184. return connect_func(self, address)
  185. result = connect_func(self, (self._proxy.host, self._proxy.port))
  186. if result != 0 and result is not None:
  187. return result
  188. setup_funcs = {
  189. ProxyType.SOCKS4: self._setup_socks4,
  190. ProxyType.SOCKS4A: self._setup_socks4a,
  191. ProxyType.SOCKS5: self._setup_socks5,
  192. }
  193. setup_funcs[self._proxy.type](address)
  194. return result
  195. def connect(self, address):
  196. self._make_proxy(socket.socket.connect, address)
  197. def connect_ex(self, address):
  198. return self._make_proxy(socket.socket.connect_ex, address)