├── .gitignore ├── LICENSE ├── README.md ├── setup.py ├── socks.py ├── sockshandler.py └── test ├── README ├── httpproxy.py ├── mocks ├── mocks.conf ├── socks4server.py ├── sockstest.py └── test.sh /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | MANIFEST.in 28 | setup.cfg 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2006 Dan-Haim. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without modification, 4 | 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 | 14 | THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED 15 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 16 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 17 | EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 18 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 19 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA 20 | OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 21 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 22 | OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | PySocks 2 | ======= 3 | 4 | Updated and semi-actively maintained version of [SocksiPy](http://socksipy.sourceforge.net/), with bug fixes and extra features. 5 | 6 | Acts as a drop-in replacement to the socket module. 7 | 8 | ---------------- 9 | 10 | Features 11 | ======== 12 | 13 | * SOCKS proxy client for Python 2.6 - 3.x 14 | * TCP and UDP both supported 15 | * HTTP proxy client included but not supported or recommended (you should use urllib2's or requests' own HTTP proxy interface) 16 | * urllib2 handler included. `pip install` / `setup.py install` will automatically install the `sockshandler` module. 17 | 18 | Installation 19 | ============ 20 | 21 | pip install PySocks 22 | 23 | Or download the tarball / `git clone` and... 24 | 25 | python setup.py install 26 | 27 | These will install both the `socks` and `sockshandler` modules. 28 | 29 | Alternatively, include just `socks.py` in your project. 30 | 31 | -------------------------------------------- 32 | 33 | *Warning:* PySocks/SocksiPy only supports HTTP proxies that use CONNECT tunneling. Certain HTTP proxies may not work with this library. If you wish to use HTTP (not SOCKS) proxies, it is recommended that you rely on your HTTP client's native proxy support (`proxies` dict for `requests`, or `urllib2.ProxyHandler` for `urllib2`) instead. 34 | 35 | -------------------------------------------- 36 | 37 | Usage 38 | ===== 39 | 40 | ## socks.socksocket ## 41 | 42 | import socks 43 | 44 | s = socks.socksocket() # Same API as socket.socket in the standard lib 45 | 46 | s.set_proxy(socks.SOCKS5, "localhost") # SOCKS4 and SOCKS5 use port 1080 by default 47 | # Or 48 | s.set_proxy(socks.SOCKS4, "localhost", 4444) 49 | # Or 50 | s.set_proxy(socks.HTTP, "5.5.5.5", 8888) 51 | 52 | # Can be treated identical to a regular socket object 53 | s.connect(("www.somesite.com", 80)) 54 | s.sendall("GET / HTTP/1.1 ...") 55 | print s.recv(4096) 56 | 57 | ## Monkeypatching ## 58 | 59 | To monkeypatch the entire standard library with a single default proxy: 60 | 61 | import urllib2 62 | import socket 63 | import socks 64 | 65 | socks.set_default_proxy(socks.SOCKS5, "localhost") 66 | socket.socket = socks.socksocket 67 | 68 | urllib2.urlopen("http://www.somesite.com/") # All requests will pass through the SOCKS proxy 69 | 70 | Note that monkeypatching may not work for all standard modules or for all third party modules, and generally isn't recommended. Monkeypatching is usually an anti-pattern in Python. 71 | 72 | ## urllib2 Handler ## 73 | 74 | Example use case with the `sockshandler` urllib2 handler. Note that you must import both `socks` and `sockshandler`, as the handler is its own module separate from PySocks. The module is included in the PyPI package. 75 | 76 | import urllib2 77 | import socks 78 | from sockshandler import SocksiPyHandler 79 | 80 | opener = urllib2.build_opener(SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 9050)) 81 | print opener.open("http://www.somesite.com/") # All requests made by the opener will pass through the SOCKS proxy 82 | 83 | -------------------------------------------- 84 | 85 | Original SocksiPy README attached below, amended to reflect API changes. 86 | 87 | -------------------------------------------- 88 | 89 | SocksiPy 90 | 91 | A Python SOCKS module. 92 | 93 | (C) 2006 Dan-Haim. All rights reserved. 94 | 95 | See LICENSE file for details. 96 | 97 | 98 | *WHAT IS A SOCKS PROXY?* 99 | 100 | A SOCKS proxy is a proxy server at the TCP level. In other words, it acts as 101 | a tunnel, relaying all traffic going through it without modifying it. 102 | SOCKS proxies can be used to relay traffic using any network protocol that 103 | uses TCP. 104 | 105 | *WHAT IS SOCKSIPY?* 106 | 107 | This Python module allows you to create TCP connections through a SOCKS 108 | proxy without any special effort. 109 | It also supports relaying UDP packets with a SOCKS5 proxy. 110 | 111 | *PROXY COMPATIBILITY* 112 | 113 | SocksiPy is compatible with three different types of proxies: 114 | 115 | 1. SOCKS Version 4 (SOCKS4), including the SOCKS4a extension. 116 | 2. SOCKS Version 5 (SOCKS5). 117 | 3. HTTP Proxies which support tunneling using the CONNECT method. 118 | 119 | *SYSTEM REQUIREMENTS* 120 | 121 | Being written in Python, SocksiPy can run on any platform that has a Python 122 | interpreter and TCP/IP support. 123 | This module has been tested with Python 2.3 and should work with greater versions 124 | just as well. 125 | 126 | 127 | INSTALLATION 128 | ------------- 129 | 130 | Simply copy the file "socks.py" to your Python's `lib/site-packages` directory, 131 | and you're ready to go. [Editor's note: it is better to use `python setup.py install` for PySocks] 132 | 133 | 134 | USAGE 135 | ------ 136 | 137 | First load the socks module with the command: 138 | 139 | >>> import socks 140 | >>> 141 | 142 | The socks module provides a class called `socksocket`, which is the base to all of the module's functionality. 143 | 144 | The `socksocket` object has the same initialization parameters as the normal socket 145 | object to ensure maximal compatibility, however it should be noted that `socksocket` will only function with family being `AF_INET` and 146 | type being either `SOCK_STREAM` or `SOCK_DGRAM`. 147 | Generally, it is best to initialize the `socksocket` object with no parameters 148 | 149 | >>> s = socks.socksocket() 150 | >>> 151 | 152 | The `socksocket` object has an interface which is very similiar to socket's (in fact 153 | the `socksocket` class is derived from socket) with a few extra methods. 154 | To select the proxy server you would like to use, use the `set_proxy` method, whose 155 | syntax is: 156 | 157 | set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) 158 | 159 | Explanation of the parameters: 160 | 161 | `proxy_type` - The type of the proxy server. This can be one of three possible 162 | choices: `PROXY_TYPE_SOCKS4`, `PROXY_TYPE_SOCKS5` and `PROXY_TYPE_HTTP` for SOCKS4, 163 | SOCKS5 and HTTP servers respectively. `SOCKS4`, `SOCKS5`, and `HTTP` are all aliases, respectively. 164 | 165 | `addr` - The IP address or DNS name of the proxy server. 166 | 167 | `port` - The port of the proxy server. Defaults to 1080 for socks and 8080 for http. 168 | 169 | `rdns` - This is a boolean flag than modifies the behavior regarding DNS resolving. 170 | If it is set to True, DNS resolving will be preformed remotely, on the server. 171 | If it is set to False, DNS resolving will be preformed locally. Please note that 172 | setting this to True with SOCKS4 servers actually use an extension to the protocol, 173 | called SOCKS4a, which may not be supported on all servers (SOCKS5 and http servers 174 | always support DNS). The default is True. 175 | 176 | `username` - For SOCKS5 servers, this allows simple username / password authentication 177 | with the server. For SOCKS4 servers, this parameter will be sent as the userid. 178 | This parameter is ignored if an HTTP server is being used. If it is not provided, 179 | authentication will not be used (servers may accept unauthenticated requests). 180 | 181 | `password` - This parameter is valid only for SOCKS5 servers and specifies the 182 | respective password for the username provided. 183 | 184 | Example of usage: 185 | 186 | >>> s.set_proxy(socks.SOCKS5, "socks.example.com") # uses default port 1080 187 | >>> s.set_proxy(socks.SOCKS4, "socks.test.com", 1081) 188 | 189 | After the set_proxy method has been called, simply call the connect method with the 190 | traditional parameters to establish a connection through the proxy: 191 | 192 | >>> s.connect(("www.sourceforge.net", 80)) 193 | >>> 194 | 195 | Connection will take a bit longer to allow negotiation with the proxy server. 196 | Please note that calling connect without calling `set_proxy` earlier will connect 197 | without a proxy (just like a regular socket). 198 | 199 | Errors: Any errors in the connection process will trigger exceptions. The exception 200 | may either be generated by the underlying socket layer or may be custom module 201 | exceptions, whose details follow: 202 | 203 | class `ProxyError` - This is a base exception class. It is not raised directly but 204 | rather all other exception classes raised by this module are derived from it. 205 | This allows an easy way to catch all proxy-related errors. It descends from `IOError`. 206 | 207 | All `ProxyError` exceptions have an attribute `socket_err`, which will contain either a 208 | caught `socket.error` exception, or `None` if there wasn't any. 209 | 210 | class `GeneralProxyError` - When thrown, it indicates a problem which does not fall 211 | into another category. 212 | 213 | * `Sent invalid data` - This error means that unexpected data has been received from 214 | the server. The most common reason is that the server specified as the proxy is 215 | not really a SOCKS4/SOCKS5/HTTP proxy, or maybe the proxy type specified is wrong. 216 | 217 | * `Connection closed unexpectedly` - The proxy server unexpectedly closed the connection. 218 | This may indicate that the proxy server is experiencing network or software problems. 219 | 220 | * `Bad proxy type` - This will be raised if the type of the proxy supplied to the 221 | set_proxy function was not one of `SOCKS4`/`SOCKS5`/`HTTP`. 222 | 223 | * `Bad input` - This will be raised if the `connect()` method is called with bad input 224 | parameters. 225 | 226 | class `SOCKS5AuthError` - This indicates that the connection through a SOCKS5 server 227 | failed due to an authentication problem. 228 | 229 | * `Authentication is required` - This will happen if you use a SOCKS5 server which 230 | requires authentication without providing a username / password at all. 231 | 232 | * `All offered authentication methods were rejected` - This will happen if the proxy 233 | requires a special authentication method which is not supported by this module. 234 | 235 | * `Unknown username or invalid password` - Self descriptive. 236 | 237 | class `SOCKS5Error` - This will be raised for SOCKS5 errors which are not related to 238 | authentication. 239 | The parameter is a tuple containing a code, as given by the server, 240 | and a description of the 241 | error. The possible errors, according to the RFC, are: 242 | 243 | * `0x01` - General SOCKS server failure - If for any reason the proxy server is unable to 244 | fulfill your request (internal server error). 245 | * `0x02` - connection not allowed by ruleset - If the address you're trying to connect to 246 | is blacklisted on the server or requires authentication. 247 | * `0x03` - Network unreachable - The target could not be contacted. A router on the network 248 | had replied with a destination net unreachable error. 249 | * `0x04` - Host unreachable - The target could not be contacted. A router on the network 250 | had replied with a destination host unreachable error. 251 | * `0x05` - Connection refused - The target server has actively refused the connection 252 | (the requested port is closed). 253 | * `0x06` - TTL expired - The TTL value of the SYN packet from the proxy to the target server 254 | has expired. This usually means that there are network problems causing the packet 255 | to be caught in a router-to-router "ping-pong". 256 | * `0x07` - Command not supported - For instance if the server does not support UDP. 257 | * `0x08` - Address type not supported - The client has provided an invalid address type. 258 | When using this module, this error should not occur. 259 | 260 | class `SOCKS4Error` - This will be raised for SOCKS4 errors. The parameter is a tuple 261 | containing a code and a description of the error, as given by the server. The 262 | possible error, according to the specification are: 263 | 264 | * `0x5B` - Request rejected or failed - Will be raised in the event of an failure for any 265 | reason other then the two mentioned next. 266 | * `0x5C` - request rejected because SOCKS server cannot connect to identd on the client - 267 | The Socks server had tried an ident lookup on your computer and has failed. In this 268 | case you should run an identd server and/or configure your firewall to allow incoming 269 | connections to local port 113 from the remote server. 270 | * `0x5D` - request rejected because the client program and identd report different user-ids - 271 | The Socks server had performed an ident lookup on your computer and has received a 272 | different userid than the one you have provided. Change your userid (through the 273 | username parameter of the set_proxy method) to match and try again. 274 | 275 | class `HTTPError` - This will be raised for HTTP errors. The message will contain 276 | the HTTP status code and provided error message. 277 | 278 | After establishing the connection, the object behaves like a standard socket. 279 | 280 | Methods like `makefile()` and `settimeout()` should behave just like regular sockets. 281 | Call the `close()` method to close the connection. 282 | 283 | In addition to the `socksocket` class, an additional function worth mentioning is the 284 | `set_default_proxy` function. The parameters are the same as the `set_proxy` method. 285 | This function will set default proxy settings for newly created `socksocket` objects, 286 | in which the proxy settings haven't been changed via the `set_proxy` method. 287 | This is quite useful if you wish to force 3rd party modules to use a SOCKS proxy, 288 | by overriding the socket object. 289 | For example: 290 | 291 | >>> socks.set_default_proxy(socks.SOCKS5, "socks.example.com") 292 | >>> socket.socket = socks.socksocket 293 | >>> urllib.urlopen("http://www.sourceforge.net/") 294 | 295 | 296 | PROBLEMS 297 | --------- 298 | 299 | Please open a GitHub issue at https://github.com/Anorov/PySocks 300 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from distutils.core import setup 3 | 4 | VERSION = "1.5.7" 5 | 6 | setup( 7 | name = "PySocks", 8 | version = VERSION, 9 | description = "A Python SOCKS client module. See https://github.com/Anorov/PySocks for more information.", 10 | url = "https://github.com/Anorov/PySocks", 11 | license = "BSD", 12 | author = "Anorov", 13 | author_email = "anorov.vorona@gmail.com", 14 | keywords = ["socks", "proxy"], 15 | py_modules=["socks", "sockshandler"] 16 | ) 17 | 18 | -------------------------------------------------------------------------------- /socks.py: -------------------------------------------------------------------------------- 1 | """ 2 | SocksiPy - Python SOCKS module. 3 | Version 1.5.7 4 | 5 | Copyright 2006 Dan-Haim. All rights reserved. 6 | 7 | Redistribution and use in source and binary forms, with or without modification, 8 | are permitted provided that the following conditions are met: 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 3. Neither the name of Dan Haim nor the names of his contributors may be used 15 | to endorse or promote products derived from this software without specific 16 | prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED 19 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 20 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 21 | EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 22 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA 24 | OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 25 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 26 | OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. 27 | 28 | 29 | This module provides a standard socket-like interface for Python 30 | for tunneling connections through SOCKS proxies. 31 | 32 | =============================================================================== 33 | 34 | Minor modifications made by Christopher Gilbert (http://motomastyle.com/) 35 | for use in PyLoris (http://pyloris.sourceforge.net/) 36 | 37 | Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/) 38 | mainly to merge bug fixes found in Sourceforge 39 | 40 | Modifications made by Anorov (https://github.com/Anorov) 41 | -Forked and renamed to PySocks 42 | -Fixed issue with HTTP proxy failure checking (same bug that was in the old ___recvall() method) 43 | -Included SocksiPyHandler (sockshandler.py), to be used as a urllib2 handler, 44 | courtesy of e000 (https://github.com/e000): https://gist.github.com/869791#file_socksipyhandler.py 45 | -Re-styled code to make it readable 46 | -Aliased PROXY_TYPE_SOCKS5 -> SOCKS5 etc. 47 | -Improved exception handling and output 48 | -Removed irritating use of sequence indexes, replaced with tuple unpacked variables 49 | -Fixed up Python 3 bytestring handling - chr(0x03).encode() -> b"\x03" 50 | -Other general fixes 51 | -Added clarification that the HTTP proxy connection method only supports CONNECT-style tunneling HTTP proxies 52 | -Various small bug fixes 53 | """ 54 | 55 | __version__ = "1.5.7" 56 | 57 | import socket 58 | import struct 59 | from errno import EOPNOTSUPP, EINVAL, EAGAIN 60 | from io import BytesIO 61 | from os import SEEK_CUR 62 | from collections import Callable 63 | from base64 import b64encode 64 | 65 | PROXY_TYPE_SOCKS4 = SOCKS4 = 1 66 | PROXY_TYPE_SOCKS5 = SOCKS5 = 2 67 | PROXY_TYPE_HTTP = HTTP = 3 68 | 69 | PROXY_TYPES = {"SOCKS4": SOCKS4, "SOCKS5": SOCKS5, "HTTP": HTTP} 70 | PRINTABLE_PROXY_TYPES = dict(zip(PROXY_TYPES.values(), PROXY_TYPES.keys())) 71 | 72 | _orgsocket = _orig_socket = socket.socket 73 | 74 | class ProxyError(IOError): 75 | """ 76 | socket_err contains original socket.error exception. 77 | """ 78 | def __init__(self, msg, socket_err=None): 79 | self.msg = msg 80 | self.socket_err = socket_err 81 | 82 | if socket_err: 83 | self.msg += ": {0}".format(socket_err) 84 | 85 | def __str__(self): 86 | return self.msg 87 | 88 | class GeneralProxyError(ProxyError): pass 89 | class ProxyConnectionError(ProxyError): pass 90 | class SOCKS5AuthError(ProxyError): pass 91 | class SOCKS5Error(ProxyError): pass 92 | class SOCKS4Error(ProxyError): pass 93 | class HTTPError(ProxyError): pass 94 | 95 | SOCKS4_ERRORS = { 0x5B: "Request rejected or failed", 96 | 0x5C: "Request rejected because SOCKS server cannot connect to identd on the client", 97 | 0x5D: "Request rejected because the client program and identd report different user-ids" 98 | } 99 | 100 | SOCKS5_ERRORS = { 0x01: "General SOCKS server failure", 101 | 0x02: "Connection not allowed by ruleset", 102 | 0x03: "Network unreachable", 103 | 0x04: "Host unreachable", 104 | 0x05: "Connection refused", 105 | 0x06: "TTL expired", 106 | 0x07: "Command not supported, or protocol error", 107 | 0x08: "Address type not supported" 108 | } 109 | 110 | DEFAULT_PORTS = { SOCKS4: 1080, 111 | SOCKS5: 1080, 112 | HTTP: 8080 113 | } 114 | 115 | def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None): 116 | """ 117 | set_default_proxy(proxy_type, addr[, port[, rdns[, username, password]]]) 118 | 119 | Sets a default proxy which all further socksocket objects will use, 120 | unless explicitly changed. All parameters are as for socket.set_proxy(). 121 | """ 122 | socksocket.default_proxy = (proxy_type, addr, port, rdns, 123 | username.encode() if username else None, 124 | password.encode() if password else None) 125 | 126 | setdefaultproxy = set_default_proxy 127 | 128 | def get_default_proxy(): 129 | """ 130 | Returns the default proxy, set by set_default_proxy. 131 | """ 132 | return socksocket.default_proxy 133 | 134 | getdefaultproxy = get_default_proxy 135 | 136 | def wrap_module(module): 137 | """ 138 | Attempts to replace a module's socket library with a SOCKS socket. Must set 139 | a default proxy using set_default_proxy(...) first. 140 | This will only work on modules that import socket directly into the namespace; 141 | most of the Python Standard Library falls into this category. 142 | """ 143 | if socksocket.default_proxy: 144 | module.socket.socket = socksocket 145 | else: 146 | raise GeneralProxyError("No default proxy specified") 147 | 148 | wrapmodule = wrap_module 149 | 150 | def create_connection(dest_pair, proxy_type=None, proxy_addr=None, 151 | proxy_port=None, proxy_rdns=True, 152 | proxy_username=None, proxy_password=None, 153 | timeout=None, source_address=None, 154 | socket_options=None): 155 | """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object 156 | 157 | Like socket.create_connection(), but connects to proxy 158 | before returning the socket object. 159 | 160 | dest_pair - 2-tuple of (IP/hostname, port). 161 | **proxy_args - Same args passed to socksocket.set_proxy() if present. 162 | timeout - Optional socket timeout value, in seconds. 163 | source_address - tuple (host, port) for the socket to bind to as its source 164 | address before connecting (only for compatibility) 165 | """ 166 | # Remove IPv6 brackets on the remote address and proxy address. 167 | remote_host, remote_port = dest_pair 168 | if remote_host.startswith('['): 169 | remote_host = remote_host.strip('[]') 170 | if proxy_addr and proxy_addr.startswith('['): 171 | proxy_addr = proxy_addr.strip('[]') 172 | 173 | err = None 174 | 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 | 182 | if socket_options: 183 | for opt in socket_options: 184 | sock.setsockopt(*opt) 185 | 186 | if isinstance(timeout, (int, float)): 187 | sock.settimeout(timeout) 188 | 189 | if proxy_type: 190 | sock.set_proxy(proxy_type, proxy_addr, proxy_port, proxy_rdns, 191 | proxy_username, proxy_password) 192 | if source_address: 193 | sock.bind(source_address) 194 | 195 | sock.connect((remote_host, remote_port)) 196 | return sock 197 | 198 | except (socket.error, ProxyConnectionError) as e: 199 | err = e 200 | if sock: 201 | sock.close() 202 | sock = None 203 | 204 | if err: 205 | raise err 206 | 207 | raise socket.error("gai returned empty list.") 208 | 209 | class _BaseSocket(socket.socket): 210 | """Allows Python 2's "delegated" methods such as send() to be overridden 211 | """ 212 | def __init__(self, *pos, **kw): 213 | _orig_socket.__init__(self, *pos, **kw) 214 | 215 | self._savedmethods = dict() 216 | for name in self._savenames: 217 | self._savedmethods[name] = getattr(self, name) 218 | delattr(self, name) # Allows normal overriding mechanism to work 219 | 220 | _savenames = list() 221 | 222 | def _makemethod(name): 223 | return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw) 224 | for name in ("sendto", "send", "recvfrom", "recv"): 225 | method = getattr(_BaseSocket, name, None) 226 | 227 | # Determine if the method is not defined the usual way 228 | # as a function in the class. 229 | # Python 2 uses __slots__, so there are descriptors for each method, 230 | # but they are not functions. 231 | if not isinstance(method, Callable): 232 | _BaseSocket._savenames.append(name) 233 | setattr(_BaseSocket, name, _makemethod(name)) 234 | 235 | class socksocket(_BaseSocket): 236 | """socksocket([family[, type[, proto]]]) -> socket object 237 | 238 | Open a SOCKS enabled socket. The parameters are the same as 239 | those of the standard socket init. In order for SOCKS to work, 240 | you must specify family=AF_INET and proto=0. 241 | The "type" argument must be either SOCK_STREAM or SOCK_DGRAM. 242 | """ 243 | 244 | default_proxy = None 245 | 246 | def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, *args, **kwargs): 247 | if type not in (socket.SOCK_STREAM, socket.SOCK_DGRAM): 248 | msg = "Socket type must be stream or datagram, not {!r}" 249 | raise ValueError(msg.format(type)) 250 | 251 | _BaseSocket.__init__(self, family, type, proto, *args, **kwargs) 252 | self._proxyconn = None # TCP connection to keep UDP relay alive 253 | 254 | if self.default_proxy: 255 | self.proxy = self.default_proxy 256 | else: 257 | self.proxy = (None, None, None, None, None, None) 258 | self.proxy_sockname = None 259 | self.proxy_peername = None 260 | 261 | def _readall(self, file, count): 262 | """ 263 | Receive EXACTLY the number of bytes requested from the file object. 264 | Blocks until the required number of bytes have been received. 265 | """ 266 | data = b"" 267 | while len(data) < count: 268 | d = file.read(count - len(data)) 269 | if not d: 270 | raise GeneralProxyError("Connection closed unexpectedly") 271 | data += d 272 | return data 273 | 274 | def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None): 275 | """set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) 276 | Sets the proxy to be used. 277 | 278 | proxy_type - The type of the proxy to be used. Three types 279 | are supported: PROXY_TYPE_SOCKS4 (including socks4a), 280 | PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP 281 | addr - The address of the server (IP or DNS). 282 | port - The port of the server. Defaults to 1080 for SOCKS 283 | servers and 8080 for HTTP proxy servers. 284 | rdns - Should DNS queries be performed on the remote side 285 | (rather than the local side). The default is True. 286 | Note: This has no effect with SOCKS4 servers. 287 | username - Username to authenticate with to the server. 288 | The default is no authentication. 289 | password - Password to authenticate with to the server. 290 | Only relevant when username is also provided. 291 | """ 292 | self.proxy = (proxy_type, addr, port, rdns, 293 | username.encode() if username else None, 294 | password.encode() if password else None) 295 | 296 | setproxy = set_proxy 297 | 298 | def bind(self, *pos, **kw): 299 | """ 300 | Implements proxy connection for UDP sockets, 301 | which happens during the bind() phase. 302 | """ 303 | proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy 304 | if not proxy_type or self.type != socket.SOCK_DGRAM: 305 | return _orig_socket.bind(self, *pos, **kw) 306 | 307 | if self._proxyconn: 308 | raise socket.error(EINVAL, "Socket already bound to an address") 309 | if proxy_type != SOCKS5: 310 | msg = "UDP only supported by SOCKS5 proxy type" 311 | raise socket.error(EOPNOTSUPP, msg) 312 | _BaseSocket.bind(self, *pos, **kw) 313 | 314 | # Need to specify actual local port because 315 | # some relays drop packets if a port of zero is specified. 316 | # Avoid specifying host address in case of NAT though. 317 | _, port = self.getsockname() 318 | dst = ("0", port) 319 | 320 | self._proxyconn = _orig_socket() 321 | proxy = self._proxy_addr() 322 | self._proxyconn.connect(proxy) 323 | 324 | UDP_ASSOCIATE = b"\x03" 325 | _, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst) 326 | 327 | # The relay is most likely on the same host as the SOCKS proxy, 328 | # but some proxies return a private IP address (10.x.y.z) 329 | host, _ = proxy 330 | _, port = relay 331 | _BaseSocket.connect(self, (host, port)) 332 | self.proxy_sockname = ("0.0.0.0", 0) # Unknown 333 | 334 | def sendto(self, bytes, *args, **kwargs): 335 | if self.type != socket.SOCK_DGRAM: 336 | return _BaseSocket.sendto(self, bytes, *args, **kwargs) 337 | if not self._proxyconn: 338 | self.bind(("", 0)) 339 | 340 | address = args[-1] 341 | flags = args[:-1] 342 | 343 | header = BytesIO() 344 | RSV = b"\x00\x00" 345 | header.write(RSV) 346 | STANDALONE = b"\x00" 347 | header.write(STANDALONE) 348 | self._write_SOCKS5_address(address, header) 349 | 350 | sent = _BaseSocket.send(self, header.getvalue() + bytes, *flags, **kwargs) 351 | return sent - header.tell() 352 | 353 | def send(self, bytes, flags=0, **kwargs): 354 | if self.type == socket.SOCK_DGRAM: 355 | return self.sendto(bytes, flags, self.proxy_peername, **kwargs) 356 | else: 357 | return _BaseSocket.send(self, bytes, flags, **kwargs) 358 | 359 | def recvfrom(self, bufsize, flags=0): 360 | if self.type != socket.SOCK_DGRAM: 361 | return _BaseSocket.recvfrom(self, bufsize, flags) 362 | if not self._proxyconn: 363 | self.bind(("", 0)) 364 | 365 | buf = BytesIO(_BaseSocket.recv(self, bufsize, flags)) 366 | buf.seek(+2, SEEK_CUR) 367 | frag = buf.read(1) 368 | if ord(frag): 369 | raise NotImplementedError("Received UDP packet fragment") 370 | fromhost, fromport = self._read_SOCKS5_address(buf) 371 | 372 | if self.proxy_peername: 373 | peerhost, peerport = self.proxy_peername 374 | if fromhost != peerhost or peerport not in (0, fromport): 375 | raise socket.error(EAGAIN, "Packet filtered") 376 | 377 | return (buf.read(), (fromhost, fromport)) 378 | 379 | def recv(self, *pos, **kw): 380 | bytes, _ = self.recvfrom(*pos, **kw) 381 | return bytes 382 | 383 | def close(self): 384 | if self._proxyconn: 385 | self._proxyconn.close() 386 | return _BaseSocket.close(self) 387 | 388 | def get_proxy_sockname(self): 389 | """ 390 | Returns the bound IP address and port number at the proxy. 391 | """ 392 | return self.proxy_sockname 393 | 394 | getproxysockname = get_proxy_sockname 395 | 396 | def get_proxy_peername(self): 397 | """ 398 | Returns the IP and port number of the proxy. 399 | """ 400 | return _BaseSocket.getpeername(self) 401 | 402 | getproxypeername = get_proxy_peername 403 | 404 | def get_peername(self): 405 | """ 406 | Returns the IP address and port number of the destination 407 | machine (note: get_proxy_peername returns the proxy) 408 | """ 409 | return self.proxy_peername 410 | 411 | getpeername = get_peername 412 | 413 | def _negotiate_SOCKS5(self, *dest_addr): 414 | """ 415 | Negotiates a stream connection through a SOCKS5 server. 416 | """ 417 | CONNECT = b"\x01" 418 | self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(self, 419 | CONNECT, dest_addr) 420 | 421 | def _SOCKS5_request(self, conn, cmd, dst): 422 | """ 423 | Send SOCKS5 request with given command (CMD field) and 424 | address (DST field). Returns resolved DST address that was used. 425 | """ 426 | proxy_type, addr, port, rdns, username, password = self.proxy 427 | 428 | writer = conn.makefile("wb") 429 | reader = conn.makefile("rb", 0) # buffering=0 renamed in Python 3 430 | try: 431 | # First we'll send the authentication packages we support. 432 | if username and password: 433 | # The username/password details were supplied to the 434 | # set_proxy method so we support the USERNAME/PASSWORD 435 | # authentication (in addition to the standard none). 436 | writer.write(b"\x05\x02\x00\x02") 437 | else: 438 | # No username/password were entered, therefore we 439 | # only support connections with no authentication. 440 | writer.write(b"\x05\x01\x00") 441 | 442 | # We'll receive the server's response to determine which 443 | # method was selected 444 | writer.flush() 445 | chosen_auth = self._readall(reader, 2) 446 | 447 | if chosen_auth[0:1] != b"\x05": 448 | # Note: string[i:i+1] is used because indexing of a bytestring 449 | # via bytestring[i] yields an integer in Python 3 450 | raise GeneralProxyError("SOCKS5 proxy server sent invalid data") 451 | 452 | # Check the chosen authentication method 453 | 454 | if chosen_auth[1:2] == b"\x02": 455 | # Okay, we need to perform a basic username/password 456 | # authentication. 457 | writer.write(b"\x01" + chr(len(username)).encode() 458 | + username 459 | + chr(len(password)).encode() 460 | + password) 461 | writer.flush() 462 | auth_status = self._readall(reader, 2) 463 | if auth_status[0:1] != b"\x01": 464 | # Bad response 465 | raise GeneralProxyError("SOCKS5 proxy server sent invalid data") 466 | if auth_status[1:2] != b"\x00": 467 | # Authentication failed 468 | raise SOCKS5AuthError("SOCKS5 authentication failed") 469 | 470 | # Otherwise, authentication succeeded 471 | 472 | # No authentication is required if 0x00 473 | elif chosen_auth[1:2] != b"\x00": 474 | # Reaching here is always bad 475 | if chosen_auth[1:2] == b"\xFF": 476 | raise SOCKS5AuthError("All offered SOCKS5 authentication methods were rejected") 477 | else: 478 | raise GeneralProxyError("SOCKS5 proxy server sent invalid data") 479 | 480 | # Now we can request the actual connection 481 | writer.write(b"\x05" + cmd + b"\x00") 482 | resolved = self._write_SOCKS5_address(dst, writer) 483 | writer.flush() 484 | 485 | # Get the response 486 | resp = self._readall(reader, 3) 487 | if resp[0:1] != b"\x05": 488 | raise GeneralProxyError("SOCKS5 proxy server sent invalid data") 489 | 490 | status = ord(resp[1:2]) 491 | if status != 0x00: 492 | # Connection failed: server returned an error 493 | error = SOCKS5_ERRORS.get(status, "Unknown error") 494 | raise SOCKS5Error("{0:#04x}: {1}".format(status, error)) 495 | 496 | # Get the bound address/port 497 | bnd = self._read_SOCKS5_address(reader) 498 | return (resolved, bnd) 499 | finally: 500 | reader.close() 501 | writer.close() 502 | 503 | def _write_SOCKS5_address(self, addr, file): 504 | """ 505 | Return the host and port packed for the SOCKS5 protocol, 506 | and the resolved address as a tuple object. 507 | """ 508 | host, port = addr 509 | proxy_type, _, _, rdns, username, password = self.proxy 510 | family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"} 511 | 512 | # If the given destination address is an IP address, we'll 513 | # use the IP address request even if remote resolving was specified. 514 | # Detect whether the address is IPv4/6 directly. 515 | for family in (socket.AF_INET, socket.AF_INET6): 516 | try: 517 | addr_bytes = socket.inet_pton(family, host) 518 | file.write(family_to_byte[family] + addr_bytes) 519 | host = socket.inet_ntop(family, addr_bytes) 520 | file.write(struct.pack(">H", port)) 521 | return host, port 522 | except socket.error: 523 | continue 524 | 525 | # Well it's not an IP number, so it's probably a DNS name. 526 | if rdns: 527 | # Resolve remotely 528 | host_bytes = host.encode('idna') 529 | file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes) 530 | else: 531 | # Resolve locally 532 | addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG) 533 | # We can't really work out what IP is reachable, so just pick the 534 | # first. 535 | target_addr = addresses[0] 536 | family = target_addr[0] 537 | host = target_addr[4][0] 538 | 539 | addr_bytes = socket.inet_pton(family, host) 540 | file.write(family_to_byte[family] + addr_bytes) 541 | host = socket.inet_ntop(family, addr_bytes) 542 | file.write(struct.pack(">H", port)) 543 | return host, port 544 | 545 | def _read_SOCKS5_address(self, file): 546 | atyp = self._readall(file, 1) 547 | if atyp == b"\x01": 548 | addr = socket.inet_ntoa(self._readall(file, 4)) 549 | elif atyp == b"\x03": 550 | length = self._readall(file, 1) 551 | addr = self._readall(file, ord(length)) 552 | elif atyp == b"\x04": 553 | addr = socket.inet_ntop(socket.AF_INET6, self._readall(file, 16)) 554 | else: 555 | raise GeneralProxyError("SOCKS5 proxy server sent invalid data") 556 | 557 | port = struct.unpack(">H", self._readall(file, 2))[0] 558 | return addr, port 559 | 560 | def _negotiate_SOCKS4(self, dest_addr, dest_port): 561 | """ 562 | Negotiates a connection through a SOCKS4 server. 563 | """ 564 | proxy_type, addr, port, rdns, username, password = self.proxy 565 | 566 | writer = self.makefile("wb") 567 | reader = self.makefile("rb", 0) # buffering=0 renamed in Python 3 568 | try: 569 | # Check if the destination address provided is an IP address 570 | remote_resolve = False 571 | try: 572 | addr_bytes = socket.inet_aton(dest_addr) 573 | except socket.error: 574 | # It's a DNS name. Check where it should be resolved. 575 | if rdns: 576 | addr_bytes = b"\x00\x00\x00\x01" 577 | remote_resolve = True 578 | else: 579 | addr_bytes = socket.inet_aton(socket.gethostbyname(dest_addr)) 580 | 581 | # Construct the request packet 582 | writer.write(struct.pack(">BBH", 0x04, 0x01, dest_port)) 583 | writer.write(addr_bytes) 584 | 585 | # The username parameter is considered userid for SOCKS4 586 | if username: 587 | writer.write(username) 588 | writer.write(b"\x00") 589 | 590 | # DNS name if remote resolving is required 591 | # NOTE: This is actually an extension to the SOCKS4 protocol 592 | # called SOCKS4A and may not be supported in all cases. 593 | if remote_resolve: 594 | writer.write(dest_addr.encode('idna') + b"\x00") 595 | writer.flush() 596 | 597 | # Get the response from the server 598 | resp = self._readall(reader, 8) 599 | if resp[0:1] != b"\x00": 600 | # Bad data 601 | raise GeneralProxyError("SOCKS4 proxy server sent invalid data") 602 | 603 | status = ord(resp[1:2]) 604 | if status != 0x5A: 605 | # Connection failed: server returned an error 606 | error = SOCKS4_ERRORS.get(status, "Unknown error") 607 | raise SOCKS4Error("{0:#04x}: {1}".format(status, error)) 608 | 609 | # Get the bound address/port 610 | self.proxy_sockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0]) 611 | if remote_resolve: 612 | self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port 613 | else: 614 | self.proxy_peername = dest_addr, dest_port 615 | finally: 616 | reader.close() 617 | writer.close() 618 | 619 | def _negotiate_HTTP(self, dest_addr, dest_port): 620 | """ 621 | Negotiates a connection through an HTTP server. 622 | NOTE: This currently only supports HTTP CONNECT-style proxies. 623 | """ 624 | proxy_type, addr, port, rdns, username, password = self.proxy 625 | 626 | # If we need to resolve locally, we do this now 627 | addr = dest_addr if rdns else socket.gethostbyname(dest_addr) 628 | 629 | http_headers = [ 630 | b"CONNECT " + addr.encode('idna') + b":" + str(dest_port).encode() + b" HTTP/1.1", 631 | b"Host: " + dest_addr.encode('idna') 632 | ] 633 | 634 | if username and password: 635 | http_headers.append(b"Proxy-Authorization: basic " + b64encode(username + b":" + password)) 636 | 637 | http_headers.append(b"\r\n") 638 | 639 | self.sendall(b"\r\n".join(http_headers)) 640 | 641 | # We just need the first line to check if the connection was successful 642 | fobj = self.makefile() 643 | status_line = fobj.readline() 644 | fobj.close() 645 | 646 | if not status_line: 647 | raise GeneralProxyError("Connection closed unexpectedly") 648 | 649 | try: 650 | proto, status_code, status_msg = status_line.split(" ", 2) 651 | except ValueError: 652 | raise GeneralProxyError("HTTP proxy server sent invalid response") 653 | 654 | if not proto.startswith("HTTP/"): 655 | raise GeneralProxyError("Proxy server does not appear to be an HTTP proxy") 656 | 657 | try: 658 | status_code = int(status_code) 659 | except ValueError: 660 | raise HTTPError("HTTP proxy server did not return a valid HTTP status") 661 | 662 | if status_code != 200: 663 | error = "{0}: {1}".format(status_code, status_msg) 664 | if status_code in (400, 403, 405): 665 | # It's likely that the HTTP proxy server does not support the CONNECT tunneling method 666 | error += ("\n[*] Note: The HTTP proxy server may not be supported by PySocks" 667 | " (must be a CONNECT tunnel proxy)") 668 | raise HTTPError(error) 669 | 670 | self.proxy_sockname = (b"0.0.0.0", 0) 671 | self.proxy_peername = addr, dest_port 672 | 673 | _proxy_negotiators = { 674 | SOCKS4: _negotiate_SOCKS4, 675 | SOCKS5: _negotiate_SOCKS5, 676 | HTTP: _negotiate_HTTP 677 | } 678 | 679 | 680 | def connect(self, dest_pair): 681 | """ 682 | Connects to the specified destination through a proxy. 683 | Uses the same API as socket's connect(). 684 | To select the proxy server, use set_proxy(). 685 | 686 | dest_pair - 2-tuple of (IP/hostname, port). 687 | """ 688 | if len(dest_pair) != 2 or dest_pair[0].startswith("["): 689 | # Probably IPv6, not supported -- raise an error, and hope 690 | # Happy Eyeballs (RFC6555) makes sure at least the IPv4 691 | # connection works... 692 | raise socket.error("PySocks doesn't support IPv6") 693 | 694 | dest_addr, dest_port = dest_pair 695 | 696 | if self.type == socket.SOCK_DGRAM: 697 | if not self._proxyconn: 698 | self.bind(("", 0)) 699 | dest_addr = socket.gethostbyname(dest_addr) 700 | 701 | # If the host address is INADDR_ANY or similar, reset the peer 702 | # address so that packets are received from any peer 703 | if dest_addr == "0.0.0.0" and not dest_port: 704 | self.proxy_peername = None 705 | else: 706 | self.proxy_peername = (dest_addr, dest_port) 707 | return 708 | 709 | proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy 710 | 711 | # Do a minimal input check first 712 | if (not isinstance(dest_pair, (list, tuple)) 713 | or len(dest_pair) != 2 714 | or not dest_addr 715 | or not isinstance(dest_port, int)): 716 | raise GeneralProxyError("Invalid destination-connection (host, port) pair") 717 | 718 | 719 | if proxy_type is None: 720 | # Treat like regular socket object 721 | self.proxy_peername = dest_pair 722 | _BaseSocket.connect(self, (dest_addr, dest_port)) 723 | return 724 | 725 | proxy_addr = self._proxy_addr() 726 | 727 | try: 728 | # Initial connection to proxy server 729 | _BaseSocket.connect(self, proxy_addr) 730 | 731 | except socket.error as error: 732 | # Error while connecting to proxy 733 | self.close() 734 | proxy_addr, proxy_port = proxy_addr 735 | proxy_server = "{0}:{1}".format(proxy_addr, proxy_port) 736 | printable_type = PRINTABLE_PROXY_TYPES[proxy_type] 737 | 738 | msg = "Error connecting to {0} proxy {1}".format(printable_type, 739 | proxy_server) 740 | raise ProxyConnectionError(msg, error) 741 | 742 | else: 743 | # Connected to proxy server, now negotiate 744 | try: 745 | # Calls negotiate_{SOCKS4, SOCKS5, HTTP} 746 | negotiate = self._proxy_negotiators[proxy_type] 747 | negotiate(self, dest_addr, dest_port) 748 | except socket.error as error: 749 | # Wrap socket errors 750 | self.close() 751 | raise GeneralProxyError("Socket error", error) 752 | except ProxyError: 753 | # Protocol error while negotiating with proxy 754 | self.close() 755 | raise 756 | 757 | def _proxy_addr(self): 758 | """ 759 | Return proxy address to connect to as tuple object 760 | """ 761 | proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy 762 | proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type) 763 | if not proxy_port: 764 | raise GeneralProxyError("Invalid proxy type") 765 | return proxy_addr, proxy_port 766 | -------------------------------------------------------------------------------- /sockshandler.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | SocksiPy + urllib2 handler 4 | 5 | version: 0.3 6 | author: e 7 | 8 | This module provides a Handler which you can use with urllib2 to allow it to tunnel your connection through a socks.sockssocket socket, with out monkey patching the original socket... 9 | """ 10 | import ssl 11 | 12 | try: 13 | import urllib2 14 | import httplib 15 | except ImportError: # Python 3 16 | import urllib.request as urllib2 17 | import http.client as httplib 18 | 19 | import socks # $ pip install PySocks 20 | 21 | def merge_dict(a, b): 22 | d = a.copy() 23 | d.update(b) 24 | return d 25 | 26 | class SocksiPyConnection(httplib.HTTPConnection): 27 | def __init__(self, proxytype, proxyaddr, proxyport=None, rdns=True, username=None, password=None, *args, **kwargs): 28 | self.proxyargs = (proxytype, proxyaddr, proxyport, rdns, username, password) 29 | httplib.HTTPConnection.__init__(self, *args, **kwargs) 30 | 31 | def connect(self): 32 | self.sock = socks.socksocket() 33 | self.sock.setproxy(*self.proxyargs) 34 | if type(self.timeout) in (int, float): 35 | self.sock.settimeout(self.timeout) 36 | self.sock.connect((self.host, self.port)) 37 | 38 | class SocksiPyConnectionS(httplib.HTTPSConnection): 39 | def __init__(self, proxytype, proxyaddr, proxyport=None, rdns=True, username=None, password=None, *args, **kwargs): 40 | self.proxyargs = (proxytype, proxyaddr, proxyport, rdns, username, password) 41 | httplib.HTTPSConnection.__init__(self, *args, **kwargs) 42 | 43 | def connect(self): 44 | sock = socks.socksocket() 45 | sock.setproxy(*self.proxyargs) 46 | if type(self.timeout) in (int, float): 47 | sock.settimeout(self.timeout) 48 | sock.connect((self.host, self.port)) 49 | self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file) 50 | 51 | class SocksiPyHandler(urllib2.HTTPHandler, urllib2.HTTPSHandler): 52 | def __init__(self, *args, **kwargs): 53 | self.args = args 54 | self.kw = kwargs 55 | urllib2.HTTPHandler.__init__(self) 56 | 57 | def http_open(self, req): 58 | def build(host, port=None, timeout=0, **kwargs): 59 | kw = merge_dict(self.kw, kwargs) 60 | conn = SocksiPyConnection(*self.args, host=host, port=port, timeout=timeout, **kw) 61 | return conn 62 | return self.do_open(build, req) 63 | 64 | def https_open(self, req): 65 | def build(host, port=None, timeout=0, **kwargs): 66 | kw = merge_dict(self.kw, kwargs) 67 | conn = SocksiPyConnectionS(*self.args, host=host, port=port, timeout=timeout, **kw) 68 | return conn 69 | return self.do_open(build, req) 70 | 71 | if __name__ == "__main__": 72 | import sys 73 | try: 74 | port = int(sys.argv[1]) 75 | except (ValueError, IndexError): 76 | port = 9050 77 | opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS5, "localhost", port)) 78 | print("HTTP: " + opener.open("http://httpbin.org/ip").read().decode()) 79 | print("HTTPS: " + opener.open("https://httpbin.org/ip").read().decode()) 80 | -------------------------------------------------------------------------------- /test/README: -------------------------------------------------------------------------------- 1 | Very rudimentary tests for Python 2 and Python 3. 2 | 3 | Requirements: tornado, twisted (available through pip) 4 | 5 | ./test.sh 6 | -------------------------------------------------------------------------------- /test/httpproxy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Simple asynchronous HTTP proxy with tunnelling (CONNECT). 4 | # 5 | # GET/POST proxying based on 6 | # http://groups.google.com/group/python-tornado/msg/7bea08e7a049cf26 7 | # 8 | # Copyright (C) 2012 Senko Rasic 9 | # 10 | # Permission is hereby granted, free of charge, to any person obtaining a copy 11 | # of this software and associated documentation files (the "Software"), to deal 12 | # in the Software without restriction, including without limitation the rights 13 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | # copies of the Software, and to permit persons to whom the Software is 15 | # furnished to do so, subject to the following conditions: 16 | # 17 | # The above copyright notice and this permission notice shall be included in 18 | # all copies or substantial portions of the Software. 19 | # 20 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 26 | # THE SOFTWARE. 27 | 28 | import sys 29 | import socket 30 | 31 | import tornado.httpserver 32 | import tornado.ioloop 33 | import tornado.iostream 34 | import tornado.web 35 | import tornado.httpclient 36 | 37 | __all__ = ['ProxyHandler', 'run_proxy'] 38 | 39 | 40 | class ProxyHandler(tornado.web.RequestHandler): 41 | SUPPORTED_METHODS = ['GET', 'POST', 'CONNECT'] 42 | 43 | @tornado.web.asynchronous 44 | def get(self): 45 | 46 | def handle_response(response): 47 | if response.error and not isinstance(response.error, 48 | tornado.httpclient.HTTPError): 49 | self.set_status(500) 50 | self.write('Internal server error:\n' + str(response.error)) 51 | self.finish() 52 | else: 53 | self.set_status(response.code) 54 | for header in ('Date', 'Cache-Control', 'Server', 55 | 'Content-Type', 'Location'): 56 | v = response.headers.get(header) 57 | if v: 58 | self.set_header(header, v) 59 | if response.body: 60 | self.write(response.body) 61 | self.finish() 62 | 63 | req = tornado.httpclient.HTTPRequest(url=self.request.uri, 64 | method=self.request.method, body=self.request.body, 65 | headers=self.request.headers, follow_redirects=False, 66 | allow_nonstandard_methods=True) 67 | 68 | client = tornado.httpclient.AsyncHTTPClient() 69 | try: 70 | client.fetch(req, handle_response) 71 | except tornado.httpclient.HTTPError as e: 72 | if hasattr(e, 'response') and e.response: 73 | self.handle_response(e.response) 74 | else: 75 | self.set_status(500) 76 | self.write('Internal server error:\n' + str(e)) 77 | self.finish() 78 | 79 | @tornado.web.asynchronous 80 | def post(self): 81 | return self.get() 82 | 83 | @tornado.web.asynchronous 84 | def connect(self): 85 | host, port = self.request.uri.split(':') 86 | client = self.request.connection.stream 87 | 88 | def read_from_client(data): 89 | upstream.write(data) 90 | 91 | def read_from_upstream(data): 92 | client.write(data) 93 | 94 | def client_close(data=None): 95 | if upstream.closed(): 96 | return 97 | if data: 98 | upstream.write(data) 99 | upstream.close() 100 | 101 | def upstream_close(data=None): 102 | if client.closed(): 103 | return 104 | if data: 105 | client.write(data) 106 | client.close() 107 | 108 | def start_tunnel(): 109 | client.read_until_close(client_close, read_from_client) 110 | upstream.read_until_close(upstream_close, read_from_upstream) 111 | client.write(b'HTTP/1.0 200 Connection established\r\n\r\n') 112 | 113 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) 114 | upstream = tornado.iostream.IOStream(s) 115 | upstream.connect((host, int(port)), start_tunnel) 116 | 117 | 118 | def run_proxy(port=8080, start_ioloop=True): 119 | """ 120 | Run proxy on the specified port. If start_ioloop is True (default), 121 | the tornado IOLoop will be started immediately. 122 | """ 123 | app = tornado.web.Application([ 124 | (r'.*', ProxyHandler), 125 | ]) 126 | app.listen(port, address="127.0.0.1") 127 | ioloop = tornado.ioloop.IOLoop.instance() 128 | if start_ioloop: 129 | ioloop.start() 130 | 131 | if __name__ == '__main__': 132 | port = 8081 133 | if len(sys.argv) > 1: 134 | port = int(sys.argv[1]) 135 | 136 | print ("Running HTTP proxy server") 137 | run_proxy(port) 138 | -------------------------------------------------------------------------------- /test/mocks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/breakwa11/PySocks/de2632bf9a1b8e256f805282e2b4e45cda38b913/test/mocks -------------------------------------------------------------------------------- /test/mocks.conf: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # # 3 | # Sample configuration file for MOCKS 0.0.2 # 4 | # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 5 | # # 6 | # I recommend reading the examples in this file # 7 | # and then extending it to suite your needs. # 8 | # # 9 | ################################################# 10 | 11 | 12 | 13 | ######################### 14 | # 15 | # General daemon config 16 | # ~~~~~~~~~~~~~~~~~~~~~ 17 | # 18 | ######################### 19 | 20 | PORT = 1081 # Port MOCKS is to listen to 21 | MOCKS_ADDR = 127.0.0.1 # IP adress MOCKS is to bind to 22 | LOG_FILE = mocks.log # MOCKS log file 23 | PID_FILE = mocks.pid # File holding MOCKS's process ID 24 | BUFFER_SIZE = 65536 # Traffic buffer size in bytes 25 | BACKLOG = 5 # Backlog for listen() 26 | NEGOTIATION_TIMEOUT = 5 27 | CONNECTION_IDLE_TIMEOUT = 300 28 | BIND_TIMEOUT = 30 29 | SHUTDOWN_TIMEOUT = 3 30 | MAX_CONNECTIONS = 50 31 | 32 | 33 | 34 | ########################################################################## 35 | # 36 | # Client filter config 37 | # ~~~~~~~~~~~~~~~~~~~~ 38 | # 39 | # Client filtering means sorting out which clients are allowed 40 | # connection and which are not. This is basically done like this: 41 | # MOCKS has a default behaviour regarding filtering client 42 | # connections. This behaviour is called the 'policy' and can either 43 | # be to ALLOW or to DENY the connection. After setting the policy 44 | # you can specify a list of exceptions. The action MOCKS takes 45 | # for a client matching any of these exceptions is the opposite 46 | # of the policy (that is, if the policy is set to ALLOW the exceptions 47 | # are denied and if the policy is set to DENY the exceptions are allowed). 48 | # An exception is specified in the form ip_address/mask, where mask 49 | # is optional and is an integer ranging from 0 to 32 identifying the 50 | # number of common heading bits that ip_address and the client's IP 51 | # address must have in order to yield a match. If mask is missing, 52 | # 32 will be assumed. For instance, 192.168.1.0/24 will match any IP 53 | # ranging from 192.168.1.1 to 192.168.1.255. 54 | # 55 | # Let's take two examples, one for each type of policy. Let's say we 56 | # only want to allow IPs 10.12.0.0 through 10.12.255.255, 172.23.2.5 and 57 | # 192.168.52.26 to use MOCKS. What we have to to is this: 58 | # 59 | # FILTER_POLICY = DENY 60 | # FILTER_EXCEPTION = 10.12.0.0/16 61 | # FILTER_EXCEPTION = 172.23.2.5 # implied /32 62 | # FILTER_EXCEPTION = 192.168.52.26 # implied /32 63 | # 64 | # Now, let's say this is a public proxy server, but for some reason 65 | # you don't want to let any IP ranging from 192.168.1.1 to 192.168.1.255 66 | # and neither 10.2.5.13 to connect to it: 67 | # 68 | # FILTER_POLICY = ALLOW 69 | # FILTER_EXCEPTION = 192.168.1.0/24 70 | # FILTER_EXCEPTION = 10.2.5.13 71 | # 72 | ########################################################################### 73 | 74 | FILTER_POLICY = ALLOW 75 | 76 | 77 | 78 | ############################################################################# 79 | # 80 | # Upstream proxy config 81 | # ~~~~~~~~~~~~~~~~~~~~~ 82 | # 83 | # You can choose to further relay traffic through another proxy server. 84 | # MOCKS supports upstream HTTP CONNECT, SOCKS4 and SOCKS5 proxies. You 85 | # must specify the proxy type (one of HTTPCONNECT, SOCKS4 or SOCKS5), the 86 | # proxy address and the proxy port. Optionally you can specify an user 87 | # name and a password used to authenicate to the upstream proxy. This is 88 | # pretty straight forward, so let's just take an example. Let's say you 89 | # want to use the HTTP CONNECT server at httpconnectproxy.com, on port 3128, 90 | # using the username 'foo' and the password 'bar'. You do it like this: 91 | # 92 | # UP_PROXY_TYPE = HTTPCONNECT 93 | # UP_PROXY_ADDR = httpconnectproxy.com 94 | # UP_PROXY_PORT = 3128 95 | # UP_PROXY_USER = foo # These two can be missing if you 96 | # UP_PROXY_PASSWD = bar # are not required to authenticate 97 | # 98 | ############################################################################# 99 | 100 | # UP_PROXY_TYPE = HTTPCONNECT 101 | # UP_PROXY_ADDR = 192.168.1.12 102 | # UP_PROXY_PORT = 3128 103 | 104 | 105 | -------------------------------------------------------------------------------- /test/socks4server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from twisted.internet import reactor 3 | from twisted.protocols.socks import SOCKSv4Factory 4 | 5 | def run_proxy(): 6 | reactor.listenTCP(1080, SOCKSv4Factory("/dev/null"), interface="127.0.0.1") 7 | try: 8 | reactor.run() 9 | except (KeyboardInterrupt, SystemExit): 10 | reactor.stop() 11 | 12 | if __name__ == "__main__": 13 | print "Running SOCKS4 proxy server" 14 | run_proxy() 15 | -------------------------------------------------------------------------------- /test/sockstest.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.path.append("..") 3 | import socks 4 | import socket 5 | 6 | PY3K = sys.version_info[0] == 3 7 | 8 | if PY3K: 9 | import urllib.request as urllib2 10 | else: 11 | import sockshandler 12 | import urllib2 13 | 14 | def raw_HTTP_request(): 15 | req = "GET /ip HTTP/1.1\r\n" 16 | req += "Host: ifconfig.me\r\n" 17 | req += "User-Agent: Mozilla\r\n" 18 | req += "Accept: text/html\r\n" 19 | req += "\r\n" 20 | return req.encode() 21 | 22 | def socket_HTTP_test(): 23 | s = socks.socksocket() 24 | s.set_proxy(socks.HTTP, "127.0.0.1", 8081) 25 | s.connect(("ifconfig.me", 80)) 26 | s.sendall(raw_HTTP_request()) 27 | status = s.recv(2048).splitlines()[0] 28 | assert status.startswith(b"HTTP/1.1 200") 29 | 30 | def socket_SOCKS4_test(): 31 | s = socks.socksocket() 32 | s.set_proxy(socks.SOCKS4, "127.0.0.1", 1080) 33 | s.connect(("ifconfig.me", 80)) 34 | s.sendall(raw_HTTP_request()) 35 | status = s.recv(2048).splitlines()[0] 36 | assert status.startswith(b"HTTP/1.1 200") 37 | 38 | def socket_SOCKS5_test(): 39 | s = socks.socksocket() 40 | s.set_proxy(socks.SOCKS5, "127.0.0.1", 1081) 41 | s.connect(("ifconfig.me", 80)) 42 | s.sendall(raw_HTTP_request()) 43 | status = s.recv(2048).splitlines()[0] 44 | assert status.startswith(b"HTTP/1.1 200") 45 | 46 | def SOCKS5_connect_timeout_test(): 47 | s = socks.socksocket() 48 | s.settimeout(0.0001) 49 | s.set_proxy(socks.SOCKS5, "8.8.8.8", 80) 50 | try: 51 | s.connect(("ifconfig.me", 80)) 52 | except socks.ProxyConnectionError as e: 53 | assert str(e.socket_err) == "timed out" 54 | 55 | def SOCKS5_timeout_test(): 56 | s = socks.socksocket() 57 | s.settimeout(0.0001) 58 | s.set_proxy(socks.SOCKS5, "127.0.0.1", 1081) 59 | try: 60 | s.connect(("ifconfig.me", 4444)) 61 | except socks.GeneralProxyError as e: 62 | assert str(e.socket_err) == "timed out" 63 | 64 | 65 | def socket_SOCKS5_auth_test(): 66 | # TODO: add support for this test. Will need a better SOCKS5 server. 67 | s = socks.socksocket() 68 | s.set_proxy(socks.SOCKS5, "127.0.0.1", 1081, username="a", password="b") 69 | s.connect(("ifconfig.me", 80)) 70 | s.sendall(raw_HTTP_request()) 71 | status = s.recv(2048).splitlines()[0] 72 | assert status.startswith(b"HTTP/1.1 200") 73 | 74 | def socket_HTTP_IP_test(): 75 | s = socks.socksocket() 76 | s.set_proxy(socks.HTTP, "127.0.0.1", 8081) 77 | s.connect(("133.242.129.236", 80)) 78 | s.sendall(raw_HTTP_request()) 79 | status = s.recv(2048).splitlines()[0] 80 | assert status.startswith(b"HTTP/1.1 200") 81 | 82 | def socket_SOCKS4_IP_test(): 83 | s = socks.socksocket() 84 | s.set_proxy(socks.SOCKS4, "127.0.0.1", 1080) 85 | s.connect(("133.242.129.236", 80)) 86 | s.sendall(raw_HTTP_request()) 87 | status = s.recv(2048).splitlines()[0] 88 | assert status.startswith(b"HTTP/1.1 200") 89 | 90 | def socket_SOCKS5_IP_test(): 91 | s = socks.socksocket() 92 | s.set_proxy(socks.SOCKS5, "127.0.0.1", 1081) 93 | s.connect(("133.242.129.236", 80)) 94 | s.sendall(raw_HTTP_request()) 95 | status = s.recv(2048).splitlines()[0] 96 | assert status.startswith(b"HTTP/1.1 200") 97 | 98 | def urllib2_HTTP_test(): 99 | socks.set_default_proxy(socks.HTTP, "127.0.0.1", 8081) 100 | socks.wrap_module(urllib2) 101 | status = urllib2.urlopen("http://ifconfig.me/ip").getcode() 102 | assert status == 200 103 | 104 | def urllib2_SOCKS5_test(): 105 | socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 1081) 106 | socks.wrap_module(urllib2) 107 | status = urllib2.urlopen("http://ifconfig.me/ip").getcode() 108 | assert status == 200 109 | 110 | def urllib2_handler_HTTP_test(): 111 | opener = urllib2.build_opener(sockshandler.SocksiPyHandler(socks.HTTP, "127.0.0.1", 8081)) 112 | status = opener.open("http://ifconfig.me/ip").getcode() 113 | assert status == 200 114 | 115 | def urllib2_handler_SOCKS5_test(): 116 | opener = urllib2.build_opener(sockshandler.SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 1081)) 117 | status = opener.open("http://ifconfig.me/ip").getcode() 118 | assert status == 200 119 | 120 | def global_override_HTTP_test(): 121 | socks.set_default_proxy(socks.HTTP, "127.0.0.1", 8081) 122 | good = socket.socket 123 | socket.socket = socks.socksocket 124 | status = urllib2.urlopen("http://ifconfig.me/ip").getcode() 125 | socket.socket = good 126 | assert status == 200 127 | 128 | def global_override_SOCKS5_test(): 129 | default_proxy = (socks.SOCKS5, "127.0.0.1", 1081) 130 | socks.set_default_proxy(*default_proxy) 131 | good = socket.socket 132 | socket.socket = socks.socksocket 133 | status = urllib2.urlopen("http://ifconfig.me/ip").getcode() 134 | socket.socket = good 135 | assert status == 200 136 | assert socks.get_default_proxy()[1].decode() == default_proxy[1] 137 | 138 | def bail_early_with_ipv6_test(): 139 | sock = socks.socksocket() 140 | ipv6_tuple = addr, port, flowinfo, scopeid = "::1", 1234, 0, 0 141 | try: 142 | sock.connect(ipv6_tuple) 143 | except socket.error: 144 | return 145 | else: 146 | assert False, "was expecting" 147 | 148 | def main(): 149 | print("Running tests...") 150 | socket_HTTP_test() 151 | print("1/13") 152 | socket_SOCKS4_test() 153 | print("2/13") 154 | socket_SOCKS5_test() 155 | print("3/13") 156 | if not PY3K: 157 | urllib2_handler_HTTP_test() 158 | print("3.33/13") 159 | urllib2_handler_SOCKS5_test() 160 | print("3.66/13") 161 | socket_HTTP_IP_test() 162 | print("4/13") 163 | socket_SOCKS4_IP_test() 164 | print("5/13") 165 | socket_SOCKS5_IP_test() 166 | print("6/13") 167 | SOCKS5_connect_timeout_test() 168 | print("7/13") 169 | SOCKS5_timeout_test() 170 | print("8/13") 171 | urllib2_HTTP_test() 172 | print("9/13") 173 | urllib2_SOCKS5_test() 174 | print("10/13") 175 | global_override_HTTP_test() 176 | print("11/13") 177 | global_override_SOCKS5_test() 178 | print("12/13") 179 | bail_early_with_ipv6_test() 180 | print("13/13") 181 | print("All tests ran successfully") 182 | 183 | 184 | if __name__ == "__main__": 185 | main() 186 | -------------------------------------------------------------------------------- /test/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | shopt -s expand_aliases 3 | type python2 >/dev/null 2>&1 || alias python2='python' 4 | 5 | echo "Starting proxy servers..." 6 | python2 socks4server.py > /dev/null & 7 | python2 httpproxy.py > /dev/null & 8 | ./mocks start 9 | 10 | sleep 2 11 | echo "Python 2.6 tests" 12 | python2.6 sockstest.py 13 | exit 14 | 15 | sleep 2 16 | echo "Python 2.7 tests" 17 | python2.7 sockstest.py 18 | 19 | sleep 2 20 | echo "Python 3.x tests" 21 | python3 sockstest.py 22 | 23 | pkill python2 > /dev/null 24 | ./mocks shutdown 25 | echo "Finished tests" 26 | --------------------------------------------------------------------------------