You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

271 lines
8.5 KiB

  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(IOError):
  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) and '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 becasue 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 IOError('{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:
  140. self.close()
  141. raise Socks5Error(method)
  142. if method == Socks5Auth.AUTH_USER_PASS:
  143. username = self._proxy.username.encode('utf-8')
  144. password = self._proxy.password.encode('utf-8')
  145. packet = compat_struct_pack('!B', SOCKS5_USER_AUTH_VERSION)
  146. packet += self._len_and_data(username) + self._len_and_data(password)
  147. self.sendall(packet)
  148. version, status = self._recv_bytes(2)
  149. self._check_response_version(SOCKS5_USER_AUTH_VERSION, version)
  150. if status != SOCKS5_USER_AUTH_SUCCESS:
  151. self.close()
  152. raise Socks5Error(Socks5Error.ERR_GENERAL_FAILURE)
  153. def _setup_socks5(self, address):
  154. destaddr, port = address
  155. ipaddr = self._resolve_address(destaddr, None, use_remote_dns=True)
  156. self._socks5_auth()
  157. reserved = 0
  158. packet = compat_struct_pack('!BBB', SOCKS5_VERSION, Socks5Command.CMD_CONNECT, reserved)
  159. if ipaddr is None:
  160. destaddr = destaddr.encode('utf-8')
  161. packet += compat_struct_pack('!B', Socks5AddressType.ATYP_DOMAINNAME)
  162. packet += self._len_and_data(destaddr)
  163. else:
  164. packet += compat_struct_pack('!B', Socks5AddressType.ATYP_IPV4) + ipaddr
  165. packet += compat_struct_pack('!H', port)
  166. self.sendall(packet)
  167. version, status, reserved, atype = self._recv_bytes(4)
  168. self._check_response_version(SOCKS5_VERSION, version)
  169. if status != Socks5Error.ERR_SUCCESS:
  170. self.close()
  171. raise Socks5Error(status)
  172. if atype == Socks5AddressType.ATYP_IPV4:
  173. destaddr = self.recvall(4)
  174. elif atype == Socks5AddressType.ATYP_DOMAINNAME:
  175. alen = compat_ord(self.recv(1))
  176. destaddr = self.recvall(alen)
  177. elif atype == Socks5AddressType.ATYP_IPV6:
  178. destaddr = self.recvall(16)
  179. destport = compat_struct_unpack('!H', self.recvall(2))[0]
  180. return (destaddr, destport)
  181. def _make_proxy(self, connect_func, address):
  182. if not self._proxy:
  183. return connect_func(self, address)
  184. result = connect_func(self, (self._proxy.host, self._proxy.port))
  185. if result != 0 and result is not None:
  186. return result
  187. setup_funcs = {
  188. ProxyType.SOCKS4: self._setup_socks4,
  189. ProxyType.SOCKS4A: self._setup_socks4a,
  190. ProxyType.SOCKS5: self._setup_socks5,
  191. }
  192. setup_funcs[self._proxy.type](address)
  193. return result
  194. def connect(self, address):
  195. self._make_proxy(socket.socket.connect, address)
  196. def connect_ex(self, address):
  197. return self._make_proxy(socket.socket.connect_ex, address)