Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Using socket.gethostbyname through proxy

I'm using TOR to proxy connections but am having difficulty proxying DNS lookups via socket.gethostbyname("www.yahoo.com") -- I learned that it was not sending DNS traffic via proxy by sniffing traffic with wireshark. Here's a copy of the code I'm using

import StringIO
import socket
import socks  # SocksiPy module
import stem.process
from stem.util import term

SOCKS_PORT = 7000

socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)

socket.socket = socks.socksocket

def getaddrinfo(*args):
    return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
socket.getaddrinfo = getaddrinfo

socket.gethostbyname("www.yahoo.com") <--- This line is not sending traffic via proxy

Any help is greatly appreciated!

like image 587
user3071906 Avatar asked Dec 11 '13 20:12

user3071906


2 Answers

You're calling gethostbyname in the socket module. It doesn't know anything about your SOCKS socket; it is simply interacting with your operating system's name resolution mechanisms. Setting socket.socket = socks.socksocket may affect network connections made through the socket module, but the module does not make direct connections to DNS servers to perform name resolution so replacing socket.socket has no impact on this behavior.

If you simply call the connect(...) method on a socks.socksocket object using a hostname, the proxy will perform name resolution via SOCKS:

s = socks.socksocket()
s.connect(('www.yahoo.com', 80))

If you actually want to perform raw DNS queries over your SOCKS connection, you'll need to find a Python DNS module to which you can provide your socksocket object.

like image 77
larsks Avatar answered Oct 04 '22 09:10

larsks


If you resolve the DNS yourself with Socks5 you may leak information about your own computer. Instead try tunneling with Proxifier, then to Tor. Alternatively you can use SocksiPy's Socks4A extension. This will make sure information is not leaked.

like image 31
FlameBlazer Avatar answered Oct 04 '22 09:10

FlameBlazer