"""SocksiPy - Python SOCKS module.
Copyright 2006 Dan-Haim. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of Dan Haim nor the names of his contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This module provides a standard socket-like interface for Python
for tunneling connections through SOCKS proxies.
===============================================================================
Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
for use in PyLoris (http://pyloris.sourceforge.net/)
Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
mainly to merge bug fixes found in Sourceforge
Modifications made by Anorov (https://github.com/Anorov)
-Forked and renamed to PySocks
-Fixed issue with HTTP proxy failure checking (same bug that was in the
-Included SocksiPyHandler (sockshandler.py), to be used as a urllib2 handler,
courtesy of e000 (https://github.com/e000):
https://gist.github.com/869791#file_socksipyhandler.py
-Re-styled code to make it readable
-Aliased PROXY_TYPE_SOCKS5 -> SOCKS5 etc.
-Improved exception handling and output
-Removed irritating use of sequence indexes, replaced with tuple unpacked
-Fixed up Python 3 bytestring handling - chr(0x03).encode() -> b"\x03"
-Added clarification that the HTTP proxy connection method only supports
CONNECT-style tunneling HTTP proxies
from base64 import b64encode
from collections import Callable
from errno import EOPNOTSUPP, EINVAL, EAGAIN
if os.name == "nt" and sys.version_info < (3, 0):
"To run PySocks on Windows you must install win_inet_pton")
log = logging.getLogger(__name__)
PROXY_TYPE_SOCKS4 = SOCKS4 = 1
PROXY_TYPE_SOCKS5 = SOCKS5 = 2
PROXY_TYPE_HTTP = HTTP = 3
PROXY_TYPES = {"SOCKS4": SOCKS4, "SOCKS5": SOCKS5, "HTTP": HTTP}
PRINTABLE_PROXY_TYPES = dict(zip(PROXY_TYPES.values(), PROXY_TYPES.keys()))
_orgsocket = _orig_socket = socket.socket
def set_self_blocking(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
_is_blocking = self.gettimeout()
return function(*args, **kwargs)
class ProxyError(IOError):
"""Socket_err contains original socket.error exception."""
def __init__(self, msg, socket_err=None):
self.socket_err = socket_err
self.msg += ": {0}".format(socket_err)
class GeneralProxyError(ProxyError):
class ProxyConnectionError(ProxyError):
class SOCKS5AuthError(ProxyError):
class SOCKS5Error(ProxyError):
class SOCKS4Error(ProxyError):
class HTTPError(ProxyError):
0x5B: "Request rejected or failed",
0x5C: ("Request rejected because SOCKS server cannot connect to identd on"
0x5D: ("Request rejected because the client program and identd report"
0x01: "General SOCKS server failure",
0x02: "Connection not allowed by ruleset",
0x03: "Network unreachable",
0x04: "Host unreachable",
0x05: "Connection refused",
0x07: "Command not supported, or protocol error",
0x08: "Address type not supported"
DEFAULT_PORTS = {SOCKS4: 1080, SOCKS5: 1080, HTTP: 8080}
def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True,
username=None, password=None):
All further socksocket objects will use the default unless explicitly
changed. All parameters are as for socket.set_proxy()."""
socksocket.default_proxy = (proxy_type, addr, port, rdns,
username.encode() if username else None,
password.encode() if password else None)
def setdefaultproxy(*args, **kwargs):
if "proxytype" in kwargs:
kwargs["proxy_type"] = kwargs.pop("proxytype")
return set_default_proxy(*args, **kwargs)
"""Returns the default proxy, set by set_default_proxy."""
return socksocket.default_proxy
getdefaultproxy = get_default_proxy
"""Attempts to replace a module's socket library with a SOCKS socket.
Must set a default proxy using set_default_proxy(...) first. This will
only work on modules that import socket directly into the namespace;
most of the Python Standard Library falls into this category."""
if socksocket.default_proxy:
module.socket.socket = socksocket
raise GeneralProxyError("No default proxy specified")
def create_connection(dest_pair,
timeout=None, source_address=None,
proxy_type=None, proxy_addr=None,
proxy_port=None, proxy_rdns=True,
proxy_username=None, proxy_password=None,
"""create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object
Like socket.create_connection(), but connects to proxy
before returning the socket object.
dest_pair - 2-tuple of (IP/hostname, port).
**proxy_args - Same args passed to socksocket.set_proxy() if present.
timeout - Optional socket timeout value, in seconds.
source_address - tuple (host, port) for the socket to bind to as its source
address before connecting (only for compatibility)
# Remove IPv6 brackets on the remote address and proxy address.
remote_host, remote_port = dest_pair
if remote_host.startswith("["):
remote_host = remote_host.strip("[]")
if proxy_addr and proxy_addr.startswith("["):
proxy_addr = proxy_addr.strip("[]")
# Allow the SOCKS proxy to be on IPv4 or IPv6 addresses.
for r in socket.getaddrinfo(proxy_addr, proxy_port, 0, socket.SOCK_STREAM):
family, socket_type, proto, canonname, sa = r
sock = socksocket(family, socket_type, proto)
for opt in socket_options:
if isinstance(timeout, (int, float)):
sock.set_proxy(proxy_type, proxy_addr, proxy_port, proxy_rdns,
proxy_username, proxy_password)
sock.bind(source_address)
sock.connect((remote_host, remote_port))
except (socket.error, ProxyConnectionError) as e:
raise socket.error("gai returned empty list.")
class _BaseSocket(socket.socket):
"""Allows Python 2 delegated methods such as send() to be overridden."""
def __init__(self, *pos, **kw):
_orig_socket.__init__(self, *pos, **kw)
self._savedmethods = dict()
for name in self._savenames:
self._savedmethods[name] = getattr(self, name)
delattr(self, name) # Allows normal overriding mechanism to work
return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw)
for name in ("sendto", "send", "recvfrom", "recv"):
method = getattr(_BaseSocket, name, None)
# Determine if the method is not defined the usual way
# as a function in the class.
# Python 2 uses __slots__, so there are descriptors for each method,
# but they are not functions.
if not isinstance(method, Callable):
_BaseSocket._savenames.append(name)
setattr(_BaseSocket, name, _makemethod(name))
class socksocket(_BaseSocket):
"""socksocket([family[, type[, proto]]]) -> socket object
Open a SOCKS enabled socket. The parameters are the same as
those of the standard socket init. In order for SOCKS to work,
you must specify family=AF_INET and proto=0.
The "type" argument must be either SOCK_STREAM or SOCK_DGRAM.
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM,
proto=0, *args, **kwargs):
if type not in (socket.SOCK_STREAM, socket.SOCK_DGRAM):
msg = "Socket type must be stream or datagram, not {!r}"
raise ValueError(msg.format(type))
super(socksocket, self).__init__(family, type, proto, *args, **kwargs)
self._proxyconn = None # TCP connection to keep UDP relay alive
self.proxy = self.default_proxy
self.proxy = (None, None, None, None, None, None)
self.proxy_sockname = None
self.proxy_peername = None
def _readall(self, file, count):
"""Receive EXACTLY the number of bytes requested from the file object.
Blocks until the required number of bytes have been received."""
d = file.read(count - len(data))
raise GeneralProxyError("Connection closed unexpectedly")
def settimeout(self, timeout):
# test if we're connected, if so apply timeout
peer = self.get_proxy_peername()
super(socksocket, self).settimeout(self._timeout)
def setblocking(self, v):
def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True,
username=None, password=None):
""" Sets the proxy to be used.
proxy_type - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (IP or DNS).
port - The port of the server. Defaults to 1080 for SOCKS
servers and 8080 for HTTP proxy servers.
rdns - Should DNS queries be performed on the remote side
(rather than the local side). The default is True.
Note: This has no effect with SOCKS4 servers.
username - Username to authenticate with to the server.
The default is no authentication.
password - Password to authenticate with to the server.
Only relevant when username is also provided."""
self.proxy = (proxy_type, addr, port, rdns,
username.encode() if username else None,
password.encode() if password else None)
def setproxy(self, *args, **kwargs):
if "proxytype" in kwargs:
kwargs["proxy_type"] = kwargs.pop("proxytype")
return self.set_proxy(*args, **kwargs)
def bind(self, *pos, **kw):
"""Implements proxy connection for UDP sockets.
Happens during the bind() phase."""
(proxy_type, proxy_addr, proxy_port, rdns, username,
if not proxy_type or self.type != socket.SOCK_DGRAM:
return _orig_socket.bind(self, *pos, **kw)
raise socket.error(EINVAL, "Socket already bound to an address")
msg = "UDP only supported by SOCKS5 proxy type"
raise socket.error(EOPNOTSUPP, msg)
super(socksocket, self).bind(*pos, **kw)
# Need to specify actual local port because
# some relays drop packets if a port of zero is specified.
# Avoid specifying host address in case of NAT though.
_, port = self.getsockname()
self._proxyconn = _orig_socket()
proxy = self._proxy_addr()
self._proxyconn.connect(proxy)
_, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst)
# The relay is most likely on the same host as the SOCKS proxy,
# but some proxies return a private IP address (10.x.y.z)
super(socksocket, self).connect((host, port))
super(socksocket, self).settimeout(self._timeout)
self.proxy_sockname = ("0.0.0.0", 0) # Unknown
def sendto(self, bytes, *args, **kwargs):
if self.type != socket.SOCK_DGRAM:
return super(socksocket, self).sendto(bytes, *args, **kwargs)
self._write_SOCKS5_address(address, header)
sent = super(socksocket, self).send(header.getvalue() + bytes, *flags,
return sent - header.tell()
def send(self, bytes, flags=0, **kwargs):
if self.type == socket.SOCK_DGRAM:
return self.sendto(bytes, flags, self.proxy_peername, **kwargs)
return super(socksocket, self).send(bytes, flags, **kwargs)
def recvfrom(self, bufsize, flags=0):
if self.type != socket.SOCK_DGRAM:
return super(socksocket, self).recvfrom(bufsize, flags)
buf = BytesIO(super(socksocket, self).recv(bufsize + 1024, flags))
raise NotImplementedError("Received UDP packet fragment")
fromhost, fromport = self._read_SOCKS5_address(buf)
peerhost, peerport = self.proxy_peername
if fromhost != peerhost or peerport not in (0, fromport):
raise socket.error(EAGAIN, "Packet filtered")
return (buf.read(bufsize), (fromhost, fromport))
def recv(self, *pos, **kw):
bytes, _ = self.recvfrom(*pos, **kw)
return super(socksocket, self).close()
def get_proxy_sockname(self):
"""Returns the bound IP address and port number at the proxy."""
return self.proxy_sockname
getproxysockname = get_proxy_sockname
def get_proxy_peername(self):
Returns the IP and port number of the proxy.
return self.getpeername()
getproxypeername = get_proxy_peername
"""Returns the IP address and port number of the destination machine.
Note: get_proxy_peername returns the proxy."""
return self.proxy_peername
getpeername = get_peername
def _negotiate_SOCKS5(self, *dest_addr):
"""Negotiates a stream connection through a SOCKS5 server."""
self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(
self, CONNECT, dest_addr)
def _SOCKS5_request(self, conn, cmd, dst):