DNS through a proxy?

In the past few days, I have been pulling my hair out looking around to find a good solution to prevent DNS leaks through the socks4 / 5 proxy.

I looked at the SocksiPy module (-branch) and tried to wrap a few things (urllib, urllib2, dnstools), but all of them are still experiencing a DNS query leak. Also pyCurl.

I know that proxychains / proxyresolv can send DNS queries through the socks4 / 5 proxy, and it does its best with some LD_PRELOAD libraries for monkey-patch socket functions like SocksiPy, but I can't seem why it doesn't sends DNS through a socks4 or socks5 proxy.

I suppose for linux, I can use CTypes with libproxychains.so to fulfill my permission, but I am looking for something multi-platform, so I think monkey-fixing the socket module is the way to go.

Has anyone come up with a good way around this? I want to do all this in code for portability convenience, and I don't want to resort to running another proxy server!

Thank!

+13
python proxy dns
Nov 01 '12 at 19:32
source share
1 answer

Ok, I figured it out. You need to set your default proxy server before you start using the socket (for example, before importing everything that uses it). You also need to neutralize the getaddrinfo part of the socket, then everything will be fine.

import socks import socket # Can be socks4/5 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4,'127.0.0.1', 9050) socket.socket = socks.socksocket # Magic! def getaddrinfo(*args): return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))] socket.getaddrinfo = getaddrinfo import urllib 

This works and proxies all DNS queries through any module that you import instead of urllib. Hope this helps someone out there!

EDIT: You can find updated code and more on my blog

+17
Nov 03 '12 at 10:40
source share



All Articles