socks.py 8.7 KB

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