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.

870 lines
32 KiB

4 years ago
  1. """SocksiPy - Python SOCKS module.
  2. Copyright 2006 Dan-Haim. All rights reserved.
  3. Redistribution and use in source and binary forms, with or without
  4. modification, are permitted provided that the following conditions are met:
  5. 1. Redistributions of source code must retain the above copyright notice, this
  6. list of conditions and the following disclaimer.
  7. 2. Redistributions in binary form must reproduce the above copyright notice,
  8. this list of conditions and the following disclaimer in the documentation
  9. and/or other materials provided with the distribution.
  10. 3. Neither the name of Dan Haim nor the names of his contributors may be used
  11. to endorse or promote products derived from this software without specific
  12. prior written permission.
  13. THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
  14. WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  15. MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  16. EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  17. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  18. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
  19. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  20. LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  21. OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22. This module provides a standard socket-like interface for Python
  23. for tunneling connections through SOCKS proxies.
  24. ===============================================================================
  25. Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
  26. for use in PyLoris (http://pyloris.sourceforge.net/)
  27. Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
  28. mainly to merge bug fixes found in Sourceforge
  29. Modifications made by Anorov (https://github.com/Anorov)
  30. -Forked and renamed to PySocks
  31. -Fixed issue with HTTP proxy failure checking (same bug that was in the
  32. old ___recvall() method)
  33. -Included SocksiPyHandler (sockshandler.py), to be used as a urllib2 handler,
  34. courtesy of e000 (https://github.com/e000):
  35. https://gist.github.com/869791#file_socksipyhandler.py
  36. -Re-styled code to make it readable
  37. -Aliased PROXY_TYPE_SOCKS5 -> SOCKS5 etc.
  38. -Improved exception handling and output
  39. -Removed irritating use of sequence indexes, replaced with tuple unpacked
  40. variables
  41. -Fixed up Python 3 bytestring handling - chr(0x03).encode() -> b"\x03"
  42. -Other general fixes
  43. -Added clarification that the HTTP proxy connection method only supports
  44. CONNECT-style tunneling HTTP proxies
  45. -Various small bug fixes
  46. """
  47. from base64 import b64encode
  48. from collections import Callable
  49. from errno import EOPNOTSUPP, EINVAL, EAGAIN
  50. import functools
  51. from io import BytesIO
  52. import logging
  53. import os
  54. from os import SEEK_CUR
  55. import socket
  56. import struct
  57. import sys
  58. __version__ = "1.6.7"
  59. if os.name == "nt" and sys.version_info < (3, 0):
  60. try:
  61. import win_inet_pton
  62. except ImportError:
  63. raise ImportError(
  64. "To run PySocks on Windows you must install win_inet_pton")
  65. log = logging.getLogger(__name__)
  66. PROXY_TYPE_SOCKS4 = SOCKS4 = 1
  67. PROXY_TYPE_SOCKS5 = SOCKS5 = 2
  68. PROXY_TYPE_HTTP = HTTP = 3
  69. PROXY_TYPES = {"SOCKS4": SOCKS4, "SOCKS5": SOCKS5, "HTTP": HTTP}
  70. PRINTABLE_PROXY_TYPES = dict(zip(PROXY_TYPES.values(), PROXY_TYPES.keys()))
  71. _orgsocket = _orig_socket = socket.socket
  72. def set_self_blocking(function):
  73. @functools.wraps(function)
  74. def wrapper(*args, **kwargs):
  75. self = args[0]
  76. try:
  77. _is_blocking = self.gettimeout()
  78. if _is_blocking == 0:
  79. self.setblocking(True)
  80. return function(*args, **kwargs)
  81. except Exception as e:
  82. raise
  83. finally:
  84. # set orgin blocking
  85. if _is_blocking == 0:
  86. self.setblocking(False)
  87. return wrapper
  88. class ProxyError(IOError):
  89. """Socket_err contains original socket.error exception."""
  90. def __init__(self, msg, socket_err=None):
  91. self.msg = msg
  92. self.socket_err = socket_err
  93. if socket_err:
  94. self.msg += ": {0}".format(socket_err)
  95. def __str__(self):
  96. return self.msg
  97. class GeneralProxyError(ProxyError):
  98. pass
  99. class ProxyConnectionError(ProxyError):
  100. pass
  101. class SOCKS5AuthError(ProxyError):
  102. pass
  103. class SOCKS5Error(ProxyError):
  104. pass
  105. class SOCKS4Error(ProxyError):
  106. pass
  107. class HTTPError(ProxyError):
  108. pass
  109. SOCKS4_ERRORS = {
  110. 0x5B: "Request rejected or failed",
  111. 0x5C: ("Request rejected because SOCKS server cannot connect to identd on"
  112. " the client"),
  113. 0x5D: ("Request rejected because the client program and identd report"
  114. " different user-ids")
  115. }
  116. SOCKS5_ERRORS = {
  117. 0x01: "General SOCKS server failure",
  118. 0x02: "Connection not allowed by ruleset",
  119. 0x03: "Network unreachable",
  120. 0x04: "Host unreachable",
  121. 0x05: "Connection refused",
  122. 0x06: "TTL expired",
  123. 0x07: "Command not supported, or protocol error",
  124. 0x08: "Address type not supported"
  125. }
  126. DEFAULT_PORTS = {SOCKS4: 1080, SOCKS5: 1080, HTTP: 8080}
  127. def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True,
  128. username=None, password=None):
  129. """Sets a default proxy.
  130. All further socksocket objects will use the default unless explicitly
  131. changed. All parameters are as for socket.set_proxy()."""
  132. socksocket.default_proxy = (proxy_type, addr, port, rdns,
  133. username.encode() if username else None,
  134. password.encode() if password else None)
  135. def setdefaultproxy(*args, **kwargs):
  136. if "proxytype" in kwargs:
  137. kwargs["proxy_type"] = kwargs.pop("proxytype")
  138. return set_default_proxy(*args, **kwargs)
  139. def get_default_proxy():
  140. """Returns the default proxy, set by set_default_proxy."""
  141. return socksocket.default_proxy
  142. getdefaultproxy = get_default_proxy
  143. def wrap_module(module):
  144. """Attempts to replace a module's socket library with a SOCKS socket.
  145. Must set a default proxy using set_default_proxy(...) first. This will
  146. only work on modules that import socket directly into the namespace;
  147. most of the Python Standard Library falls into this category."""
  148. if socksocket.default_proxy:
  149. module.socket.socket = socksocket
  150. else:
  151. raise GeneralProxyError("No default proxy specified")
  152. wrapmodule = wrap_module
  153. def create_connection(dest_pair,
  154. timeout=None, source_address=None,
  155. proxy_type=None, proxy_addr=None,
  156. proxy_port=None, proxy_rdns=True,
  157. proxy_username=None, proxy_password=None,
  158. socket_options=None):
  159. """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object
  160. Like socket.create_connection(), but connects to proxy
  161. before returning the socket object.
  162. dest_pair - 2-tuple of (IP/hostname, port).
  163. **proxy_args - Same args passed to socksocket.set_proxy() if present.
  164. timeout - Optional socket timeout value, in seconds.
  165. source_address - tuple (host, port) for the socket to bind to as its source
  166. address before connecting (only for compatibility)
  167. """
  168. # Remove IPv6 brackets on the remote address and proxy address.
  169. remote_host, remote_port = dest_pair
  170. if remote_host.startswith("["):
  171. remote_host = remote_host.strip("[]")
  172. if proxy_addr and proxy_addr.startswith("["):
  173. proxy_addr = proxy_addr.strip("[]")
  174. err = None
  175. # Allow the SOCKS proxy to be on IPv4 or IPv6 addresses.
  176. for r in socket.getaddrinfo(proxy_addr, proxy_port, 0, socket.SOCK_STREAM):
  177. family, socket_type, proto, canonname, sa = r
  178. sock = None
  179. try:
  180. sock = socksocket(family, socket_type, proto)
  181. if socket_options:
  182. for opt in socket_options:
  183. sock.setsockopt(*opt)
  184. if isinstance(timeout, (int, float)):
  185. sock.settimeout(timeout)
  186. if proxy_type:
  187. sock.set_proxy(proxy_type, proxy_addr, proxy_port, proxy_rdns,
  188. proxy_username, proxy_password)
  189. if source_address:
  190. sock.bind(source_address)
  191. sock.connect((remote_host, remote_port))
  192. return sock
  193. except (socket.error, ProxyConnectionError) as e:
  194. err = e
  195. if sock:
  196. sock.close()
  197. sock = None
  198. if err:
  199. raise err
  200. raise socket.error("gai returned empty list.")
  201. class _BaseSocket(socket.socket):
  202. """Allows Python 2 delegated methods such as send() to be overridden."""
  203. def __init__(self, *pos, **kw):
  204. _orig_socket.__init__(self, *pos, **kw)
  205. self._savedmethods = dict()
  206. for name in self._savenames:
  207. self._savedmethods[name] = getattr(self, name)
  208. delattr(self, name) # Allows normal overriding mechanism to work
  209. _savenames = list()
  210. def _makemethod(name):
  211. return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw)
  212. for name in ("sendto", "send", "recvfrom", "recv"):
  213. method = getattr(_BaseSocket, name, None)
  214. # Determine if the method is not defined the usual way
  215. # as a function in the class.
  216. # Python 2 uses __slots__, so there are descriptors for each method,
  217. # but they are not functions.
  218. if not isinstance(method, Callable):
  219. _BaseSocket._savenames.append(name)
  220. setattr(_BaseSocket, name, _makemethod(name))
  221. class socksocket(_BaseSocket):
  222. """socksocket([family[, type[, proto]]]) -> socket object
  223. Open a SOCKS enabled socket. The parameters are the same as
  224. those of the standard socket init. In order for SOCKS to work,
  225. you must specify family=AF_INET and proto=0.
  226. The "type" argument must be either SOCK_STREAM or SOCK_DGRAM.
  227. """
  228. default_proxy = None
  229. def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM,
  230. proto=0, *args, **kwargs):
  231. if type not in (socket.SOCK_STREAM, socket.SOCK_DGRAM):
  232. msg = "Socket type must be stream or datagram, not {!r}"
  233. raise ValueError(msg.format(type))
  234. super(socksocket, self).__init__(family, type, proto, *args, **kwargs)
  235. self._proxyconn = None # TCP connection to keep UDP relay alive
  236. if self.default_proxy:
  237. self.proxy = self.default_proxy
  238. else:
  239. self.proxy = (None, None, None, None, None, None)
  240. self.proxy_sockname = None
  241. self.proxy_peername = None
  242. self._timeout = None
  243. def _readall(self, file, count):
  244. """Receive EXACTLY the number of bytes requested from the file object.
  245. Blocks until the required number of bytes have been received."""
  246. data = b""
  247. while len(data) < count:
  248. d = file.read(count - len(data))
  249. if not d:
  250. raise GeneralProxyError("Connection closed unexpectedly")
  251. data += d
  252. return data
  253. def settimeout(self, timeout):
  254. self._timeout = timeout
  255. try:
  256. # test if we're connected, if so apply timeout
  257. peer = self.get_proxy_peername()
  258. super(socksocket, self).settimeout(self._timeout)
  259. except socket.error:
  260. pass
  261. def gettimeout(self):
  262. return self._timeout
  263. def setblocking(self, v):
  264. if v:
  265. self.settimeout(None)
  266. else:
  267. self.settimeout(0.0)
  268. def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True,
  269. username=None, password=None):
  270. """ Sets the proxy to be used.
  271. proxy_type - The type of the proxy to be used. Three types
  272. are supported: PROXY_TYPE_SOCKS4 (including socks4a),
  273. PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
  274. addr - The address of the server (IP or DNS).
  275. port - The port of the server. Defaults to 1080 for SOCKS
  276. servers and 8080 for HTTP proxy servers.
  277. rdns - Should DNS queries be performed on the remote side
  278. (rather than the local side). The default is True.
  279. Note: This has no effect with SOCKS4 servers.
  280. username - Username to authenticate with to the server.
  281. The default is no authentication.
  282. password - Password to authenticate with to the server.
  283. Only relevant when username is also provided."""
  284. self.proxy = (proxy_type, addr, port, rdns,
  285. username.encode() if username else None,
  286. password.encode() if password else None)
  287. def setproxy(self, *args, **kwargs):
  288. if "proxytype" in kwargs:
  289. kwargs["proxy_type"] = kwargs.pop("proxytype")
  290. return self.set_proxy(*args, **kwargs)
  291. def bind(self, *pos, **kw):
  292. """Implements proxy connection for UDP sockets.
  293. Happens during the bind() phase."""
  294. (proxy_type, proxy_addr, proxy_port, rdns, username,
  295. password) = self.proxy
  296. if not proxy_type or self.type != socket.SOCK_DGRAM:
  297. return _orig_socket.bind(self, *pos, **kw)
  298. if self._proxyconn:
  299. raise socket.error(EINVAL, "Socket already bound to an address")
  300. if proxy_type != SOCKS5:
  301. msg = "UDP only supported by SOCKS5 proxy type"
  302. raise socket.error(EOPNOTSUPP, msg)
  303. super(socksocket, self).bind(*pos, **kw)
  304. # Need to specify actual local port because
  305. # some relays drop packets if a port of zero is specified.
  306. # Avoid specifying host address in case of NAT though.
  307. _, port = self.getsockname()
  308. dst = ("0", port)
  309. self._proxyconn = _orig_socket()
  310. proxy = self._proxy_addr()
  311. self._proxyconn.connect(proxy)
  312. UDP_ASSOCIATE = b"\x03"
  313. _, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst)
  314. # The relay is most likely on the same host as the SOCKS proxy,
  315. # but some proxies return a private IP address (10.x.y.z)
  316. host, _ = proxy
  317. _, port = relay
  318. super(socksocket, self).connect((host, port))
  319. super(socksocket, self).settimeout(self._timeout)
  320. self.proxy_sockname = ("0.0.0.0", 0) # Unknown
  321. def sendto(self, bytes, *args, **kwargs):
  322. if self.type != socket.SOCK_DGRAM:
  323. return super(socksocket, self).sendto(bytes, *args, **kwargs)
  324. if not self._proxyconn:
  325. self.bind(("", 0))
  326. address = args[-1]
  327. flags = args[:-1]
  328. header = BytesIO()
  329. RSV = b"\x00\x00"
  330. header.write(RSV)
  331. STANDALONE = b"\x00"
  332. header.write(STANDALONE)
  333. self._write_SOCKS5_address(address, header)
  334. sent = super(socksocket, self).send(header.getvalue() + bytes, *flags,
  335. **kwargs)
  336. return sent - header.tell()
  337. def send(self, bytes, flags=0, **kwargs):
  338. if self.type == socket.SOCK_DGRAM:
  339. return self.sendto(bytes, flags, self.proxy_peername, **kwargs)
  340. else:
  341. return super(socksocket, self).send(bytes, flags, **kwargs)
  342. def recvfrom(self, bufsize, flags=0):
  343. if self.type != socket.SOCK_DGRAM:
  344. return super(socksocket, self).recvfrom(bufsize, flags)
  345. if not self._proxyconn:
  346. self.bind(("", 0))
  347. buf = BytesIO(super(socksocket, self).recv(bufsize + 1024, flags))
  348. buf.seek(2, SEEK_CUR)
  349. frag = buf.read(1)
  350. if ord(frag):
  351. raise NotImplementedError("Received UDP packet fragment")
  352. fromhost, fromport = self._read_SOCKS5_address(buf)
  353. if self.proxy_peername:
  354. peerhost, peerport = self.proxy_peername
  355. if fromhost != peerhost or peerport not in (0, fromport):
  356. raise socket.error(EAGAIN, "Packet filtered")
  357. return (buf.read(bufsize), (fromhost, fromport))
  358. def recv(self, *pos, **kw):
  359. bytes, _ = self.recvfrom(*pos, **kw)
  360. return bytes
  361. def close(self):
  362. if self._proxyconn:
  363. self._proxyconn.close()
  364. return super(socksocket, self).close()
  365. def get_proxy_sockname(self):
  366. """Returns the bound IP address and port number at the proxy."""
  367. return self.proxy_sockname
  368. getproxysockname = get_proxy_sockname
  369. def get_proxy_peername(self):
  370. """
  371. Returns the IP and port number of the proxy.
  372. """
  373. return self.getpeername()
  374. getproxypeername = get_proxy_peername
  375. def get_peername(self):
  376. """Returns the IP address and port number of the destination machine.
  377. Note: get_proxy_peername returns the proxy."""
  378. return self.proxy_peername
  379. getpeername = get_peername
  380. def _negotiate_SOCKS5(self, *dest_addr):
  381. """Negotiates a stream connection through a SOCKS5 server."""
  382. CONNECT = b"\x01"
  383. self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(
  384. self, CONNECT, dest_addr)
  385. def _SOCKS5_request(self, conn, cmd, dst):
  386. """
  387. Send SOCKS5 request with given command (CMD field) and
  388. address (DST field). Returns resolved DST address that was used.
  389. """
  390. proxy_type, addr, port, rdns, username, password = self.proxy
  391. writer = conn.makefile("wb")
  392. reader = conn.makefile("rb", 0) # buffering=0 renamed in Python 3
  393. try:
  394. # First we'll send the authentication packages we support.
  395. if username and password:
  396. # The username/password details were supplied to the
  397. # set_proxy method so we support the USERNAME/PASSWORD
  398. # authentication (in addition to the standard none).
  399. writer.write(b"\x05\x02\x00\x02")
  400. else:
  401. # No username/password were entered, therefore we
  402. # only support connections with no authentication.
  403. writer.write(b"\x05\x01\x00")
  404. # We'll receive the server's response to determine which
  405. # method was selected
  406. writer.flush()
  407. chosen_auth = self._readall(reader, 2)
  408. if chosen_auth[0:1] != b"\x05":
  409. # Note: string[i:i+1] is used because indexing of a bytestring
  410. # via bytestring[i] yields an integer in Python 3
  411. raise GeneralProxyError(
  412. "SOCKS5 proxy server sent invalid data")
  413. # Check the chosen authentication method
  414. if chosen_auth[1:2] == b"\x02":
  415. # Okay, we need to perform a basic username/password
  416. # authentication.
  417. writer.write(b"\x01" + chr(len(username)).encode()
  418. + username
  419. + chr(len(password)).encode()
  420. + password)
  421. writer.flush()
  422. auth_status = self._readall(reader, 2)
  423. if auth_status[0:1] != b"\x01":
  424. # Bad response
  425. raise GeneralProxyError(
  426. "SOCKS5 proxy server sent invalid data")
  427. if auth_status[1:2] != b"\x00":
  428. # Authentication failed
  429. raise SOCKS5AuthError("SOCKS5 authentication failed")
  430. # Otherwise, authentication succeeded
  431. # No authentication is required if 0x00
  432. elif chosen_auth[1:2] != b"\x00":
  433. # Reaching here is always bad
  434. if chosen_auth[1:2] == b"\xFF":
  435. raise SOCKS5AuthError(
  436. "All offered SOCKS5 authentication methods were"
  437. " rejected")
  438. else:
  439. raise GeneralProxyError(
  440. "SOCKS5 proxy server sent invalid data")
  441. # Now we can request the actual connection
  442. writer.write(b"\x05" + cmd + b"\x00")
  443. resolved = self._write_SOCKS5_address(dst, writer)
  444. writer.flush()
  445. # Get the response
  446. resp = self._readall(reader, 3)
  447. if resp[0:1] != b"\x05":
  448. raise GeneralProxyError(
  449. "SOCKS5 proxy server sent invalid data")
  450. status = ord(resp[1:2])
  451. if status != 0x00:
  452. # Connection failed: server returned an error
  453. error = SOCKS5_ERRORS.get(status, "Unknown error")
  454. raise SOCKS5Error("{0:#04x}: {1}".format(status, error))
  455. # Get the bound address/port
  456. bnd = self._read_SOCKS5_address(reader)
  457. super(socksocket, self).settimeout(self._timeout)
  458. return (resolved, bnd)
  459. finally:
  460. reader.close()
  461. writer.close()
  462. def _write_SOCKS5_address(self, addr, file):
  463. """
  464. Return the host and port packed for the SOCKS5 protocol,
  465. and the resolved address as a tuple object.
  466. """
  467. host, port = addr
  468. proxy_type, _, _, rdns, username, password = self.proxy
  469. family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"}
  470. # If the given destination address is an IP address, we'll
  471. # use the IP address request even if remote resolving was specified.
  472. # Detect whether the address is IPv4/6 directly.
  473. for family in (socket.AF_INET, socket.AF_INET6):
  474. try:
  475. addr_bytes = socket.inet_pton(family, host)
  476. file.write(family_to_byte[family] + addr_bytes)
  477. host = socket.inet_ntop(family, addr_bytes)
  478. file.write(struct.pack(">H", port))
  479. return host, port
  480. except socket.error:
  481. continue
  482. # Well it's not an IP number, so it's probably a DNS name.
  483. if rdns:
  484. # Resolve remotely
  485. host_bytes = host.encode("idna")
  486. file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes)
  487. else:
  488. # Resolve locally
  489. addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
  490. socket.SOCK_STREAM,
  491. socket.IPPROTO_TCP,
  492. socket.AI_ADDRCONFIG)
  493. # We can't really work out what IP is reachable, so just pick the
  494. # first.
  495. target_addr = addresses[0]
  496. family = target_addr[0]
  497. host = target_addr[4][0]
  498. addr_bytes = socket.inet_pton(family, host)
  499. file.write(family_to_byte[family] + addr_bytes)
  500. host = socket.inet_ntop(family, addr_bytes)
  501. file.write(struct.pack(">H", port))
  502. return host, port
  503. def _read_SOCKS5_address(self, file):
  504. atyp = self._readall(file, 1)
  505. if atyp == b"\x01":
  506. addr = socket.inet_ntoa(self._readall(file, 4))
  507. elif atyp == b"\x03":
  508. length = self._readall(file, 1)
  509. addr = self._readall(file, ord(length))
  510. elif atyp == b"\x04":
  511. addr = socket.inet_ntop(socket.AF_INET6, self._readall(file, 16))
  512. else:
  513. raise GeneralProxyError("SOCKS5 proxy server sent invalid data")
  514. port = struct.unpack(">H", self._readall(file, 2))[0]
  515. return addr, port
  516. def _negotiate_SOCKS4(self, dest_addr, dest_port):
  517. """Negotiates a connection through a SOCKS4 server."""
  518. proxy_type, addr, port, rdns, username, password = self.proxy
  519. writer = self.makefile("wb")
  520. reader = self.makefile("rb", 0) # buffering=0 renamed in Python 3
  521. try:
  522. # Check if the destination address provided is an IP address
  523. remote_resolve = False
  524. try:
  525. addr_bytes = socket.inet_aton(dest_addr)
  526. except socket.error:
  527. # It's a DNS name. Check where it should be resolved.
  528. if rdns:
  529. addr_bytes = b"\x00\x00\x00\x01"
  530. remote_resolve = True
  531. else:
  532. addr_bytes = socket.inet_aton(
  533. socket.gethostbyname(dest_addr))
  534. # Construct the request packet
  535. writer.write(struct.pack(">BBH", 0x04, 0x01, dest_port))
  536. writer.write(addr_bytes)
  537. # The username parameter is considered userid for SOCKS4
  538. if username:
  539. writer.write(username)
  540. writer.write(b"\x00")
  541. # DNS name if remote resolving is required
  542. # NOTE: This is actually an extension to the SOCKS4 protocol
  543. # called SOCKS4A and may not be supported in all cases.
  544. if remote_resolve:
  545. writer.write(dest_addr.encode("idna") + b"\x00")
  546. writer.flush()
  547. # Get the response from the server
  548. resp = self._readall(reader, 8)
  549. if resp[0:1] != b"\x00":
  550. # Bad data
  551. raise GeneralProxyError(
  552. "SOCKS4 proxy server sent invalid data")
  553. status = ord(resp[1:2])
  554. if status != 0x5A:
  555. # Connection failed: server returned an error
  556. error = SOCKS4_ERRORS.get(status, "Unknown error")
  557. raise SOCKS4Error("{0:#04x}: {1}".format(status, error))
  558. # Get the bound address/port
  559. self.proxy_sockname = (socket.inet_ntoa(resp[4:]),
  560. struct.unpack(">H", resp[2:4])[0])
  561. if remote_resolve:
  562. self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port
  563. else:
  564. self.proxy_peername = dest_addr, dest_port
  565. finally:
  566. reader.close()
  567. writer.close()
  568. def _negotiate_HTTP(self, dest_addr, dest_port):
  569. """Negotiates a connection through an HTTP server.
  570. NOTE: This currently only supports HTTP CONNECT-style proxies."""
  571. proxy_type, addr, port, rdns, username, password = self.proxy
  572. # If we need to resolve locally, we do this now
  573. addr = dest_addr if rdns else socket.gethostbyname(dest_addr)
  574. http_headers = [
  575. (b"CONNECT " + addr.encode("idna") + b":"
  576. + str(dest_port).encode() + b" HTTP/1.1"),
  577. b"Host: " + dest_addr.encode("idna")
  578. ]
  579. if username and password:
  580. http_headers.append(b"Proxy-Authorization: basic "
  581. + b64encode(username + b":" + password))
  582. http_headers.append(b"\r\n")
  583. self.sendall(b"\r\n".join(http_headers))
  584. # We just need the first line to check if the connection was successful
  585. fobj = self.makefile()
  586. status_line = fobj.readline()
  587. fobj.close()
  588. if not status_line:
  589. raise GeneralProxyError("Connection closed unexpectedly")
  590. try:
  591. proto, status_code, status_msg = status_line.split(" ", 2)
  592. except ValueError:
  593. raise GeneralProxyError("HTTP proxy server sent invalid response")
  594. if not proto.startswith("HTTP/"):
  595. raise GeneralProxyError(
  596. "Proxy server does not appear to be an HTTP proxy")
  597. try:
  598. status_code = int(status_code)
  599. except ValueError:
  600. raise HTTPError(
  601. "HTTP proxy server did not return a valid HTTP status")
  602. if status_code != 200:
  603. error = "{0}: {1}".format(status_code, status_msg)
  604. if status_code in (400, 403, 405):
  605. # It's likely that the HTTP proxy server does not support the
  606. # CONNECT tunneling method
  607. error += ("\n[*] Note: The HTTP proxy server may not be"
  608. " supported by PySocks (must be a CONNECT tunnel"
  609. " proxy)")
  610. raise HTTPError(error)
  611. self.proxy_sockname = (b"0.0.0.0", 0)
  612. self.proxy_peername = addr, dest_port
  613. _proxy_negotiators = {
  614. SOCKS4: _negotiate_SOCKS4,
  615. SOCKS5: _negotiate_SOCKS5,
  616. HTTP: _negotiate_HTTP
  617. }
  618. @set_self_blocking
  619. def connect(self, dest_pair):
  620. """
  621. Connects to the specified destination through a proxy.
  622. Uses the same API as socket's connect().
  623. To select the proxy server, use set_proxy().
  624. dest_pair - 2-tuple of (IP/hostname, port).
  625. """
  626. if len(dest_pair) != 2 or dest_pair[0].startswith("["):
  627. # Probably IPv6, not supported -- raise an error, and hope
  628. # Happy Eyeballs (RFC6555) makes sure at least the IPv4
  629. # connection works...
  630. raise socket.error("PySocks doesn't support IPv6: %s"
  631. % str(dest_pair))
  632. dest_addr, dest_port = dest_pair
  633. if self.type == socket.SOCK_DGRAM:
  634. if not self._proxyconn:
  635. self.bind(("", 0))
  636. dest_addr = socket.gethostbyname(dest_addr)
  637. # If the host address is INADDR_ANY or similar, reset the peer
  638. # address so that packets are received from any peer
  639. if dest_addr == "0.0.0.0" and not dest_port:
  640. self.proxy_peername = None
  641. else:
  642. self.proxy_peername = (dest_addr, dest_port)
  643. return
  644. (proxy_type, proxy_addr, proxy_port, rdns, username,
  645. password) = self.proxy
  646. # Do a minimal input check first
  647. if (not isinstance(dest_pair, (list, tuple))
  648. or len(dest_pair) != 2
  649. or not dest_addr
  650. or not isinstance(dest_port, int)):
  651. # Inputs failed, raise an error
  652. raise GeneralProxyError(
  653. "Invalid destination-connection (host, port) pair")
  654. # We set the timeout here so that we don't hang in connection or during
  655. # negotiation.
  656. super(socksocket, self).settimeout(self._timeout)
  657. if proxy_type is None:
  658. # Treat like regular socket object
  659. self.proxy_peername = dest_pair
  660. super(socksocket, self).settimeout(self._timeout)
  661. super(socksocket, self).connect((dest_addr, dest_port))
  662. return
  663. proxy_addr = self._proxy_addr()
  664. try:
  665. # Initial connection to proxy server.
  666. super(socksocket, self).connect(proxy_addr)
  667. except socket.error as error:
  668. # Error while connecting to proxy
  669. self.close()
  670. proxy_addr, proxy_port = proxy_addr
  671. proxy_server = "{0}:{1}".format(proxy_addr, proxy_port)
  672. printable_type = PRINTABLE_PROXY_TYPES[proxy_type]
  673. msg = "Error connecting to {0} proxy {1}".format(printable_type,
  674. proxy_server)
  675. log.debug("%s due to: %s", msg, error)
  676. raise ProxyConnectionError(msg, error)
  677. else:
  678. # Connected to proxy server, now negotiate
  679. try:
  680. # Calls negotiate_{SOCKS4, SOCKS5, HTTP}
  681. negotiate = self._proxy_negotiators[proxy_type]
  682. negotiate(self, dest_addr, dest_port)
  683. except socket.error as error:
  684. # Wrap socket errors
  685. self.close()
  686. raise GeneralProxyError("Socket error", error)
  687. except ProxyError:
  688. # Protocol error while negotiating with proxy
  689. self.close()
  690. raise
  691. def _proxy_addr(self):
  692. """
  693. Return proxy address to connect to as tuple object
  694. """
  695. (proxy_type, proxy_addr, proxy_port, rdns, username,
  696. password) = self.proxy
  697. proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type)
  698. if not proxy_port:
  699. raise GeneralProxyError("Invalid proxy type")
  700. return proxy_addr, proxy_port