I’ve been working on a proxy testing application in Clojure and have been thinking about porting it to Python. There are a couple of Python libraries that I could use to test the status of a SOCKS proxy. PyCurl is a Python wrapper of the C library curl, this makes it easy to do HTTP requests by using a SOCKS proxy. Another option is socksipy which essentially provides a wrapper around an instance of the socket module. Both of these establish a full connection with the proxy.
Looking at the SOCKS5 protocol we can see that it’s possible to test the status of a SOCKS5 proxy just by reading the response to the initial greeting packet. Both PyCurl and socksipy establish a full SOCKS connection with the server. This full connection is necessary if we want to send data through the proxy, but because we only need to check the status of the proxy, we can write a script to send just the first packet and read the response.
The format of the greeting packet is as follows (source):
- field 1: SOCKS version number (must be 0×05 for this version)
- field 2: number of authentication methods supported, 1 byte
- field 3: authentication methods, variable length, 1 byte per method supported
And the server responds:
- field 1: SOCKS version, 1 byte (0×05 for this version)
- field 2: chosen authentication method, 1 byte, or 0xFF if no acceptable methods were offered
Using Python we can write a small script to test this:
import socket
import struct
sen = struct.pack('BBB', 0x05, 0x01, 0x00)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 9050))
s.sendall(sen)
data = s.recv(2)
version, auth = struct.unpack('BB', data)
s.close()
If version is 5 and auth is 0 (no authentication), then the proxy is up and available for us to connect to.