I'm trying to use SocksIPy with ssl module (from stdlib) to grab a site's remote certificate but SocksIPy won't play with ssl.
The below code will connect to check.torproject.org and state we are not using Tor (meaning SocksIPy is not working) (bad).
Not sure if SocksIPy is the best solution for this but I haven't been able to find any other way to proxify a raw socket (or get pycurl/urllib2 to use SOCKS proxies and give SSL certs!).
To clarify, my issue is that the socket is not being proxied. I'd like to get the ssl certificate with a proxy of my choosing, that's not happening.
Seems right now, I can either have proxy or SSL but not both. Help!
import socks
import ssl
s = socks.socksocket()
s.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
ss = ssl.wrap_socket(s)
ss.connect(('check.torproject.org', 443))
ss.write("""GET / HTTP/1.0\r
Host: check.torproject.org\r\n\r\n""")
# print ss.getpeercert()
print ss.read(), ss.read(), ss.read()
ss.close()
I have tested this code while running tcpdump so it should work.
import socks
import ssl
s = socks.socksocket()
s.setproxy(socks.PROXY_TYPE_SOCKS5,"127.0.0.1",port=9050)
s.connect(('83.94.121.246', 443))
ss = ssl.wrap_socket(s)
print ss.send("hello")
ss.close()
I didn't review the ssl.py but I guess you have to call connect on the socks object and not the ssl object.
Put ssl.wrap_socket
below connect
. It doesn't work properly otherwise.
Use validation and CA certfile Getting the certificate from the server requires creating the SSL object with validation turned on and giving it a CA certificates file. If you can't find one on your system you could download the one provided by the CURL project based on Mozilla's as a local file: http://curl.haxx.se/docs/caextract.html
Note: the SocksIPy project hasn't been updated in quite a while and doesn't support Python 3.
Fixed version of original code:
import socks
import ssl
s = socks.socksocket()
s.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", port=9050)
s.connect(('check.torproject.org', 443))
ss = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs="cacert.pem")
print "Peer cert: ", ss.getpeercert()
ss.write("""GET / HTTP/1.0\r\nHost: check.torproject.org\r\n\r\n""")
content = []
while True:
data = ss.read()
if not data: break
content.append(data)
ss.close()
content = "".join(content)
assert "This browser is configured to use Tor" in content