Quickpost: Code To Connect To Tor Onion Service

I wanted a program to connect to Tor Onion Services (aka hidden services). It’s written in Python and uses the PySocks module:

import socks

PROXYHOST = ‘localhost’
PROXYPORT = 9050

HOST = ‘duskgytldkxiuqc6.onion’
PORT = 80

print(’[*] Creating socket’)
oSocket = socks.socksocket()

print(’[*] Setting SOCKS5 proxy %s %s’ % (PROXYHOST, PROXYPORT))
oSocket.set_proxy(socks.SOCKS5, PROXYHOST, PROXYPORT)

print(’[*] Connecting %s %s’ % (HOST, PORT))
oSocket.connect((HOST, PORT))

print(’[*] Sending’)
data = [‘GET / HTTP/1.1’, ‘Host: %s’ % HOST]
data = ‘\r\n’.join(data) + ‘\r\n\r\n’
print(data)
oSocket.sendall(data.encode(‘ascii’))

print(’[*] Receiving’)
print(oSocket.recv(0x1000))

print(’[*] Closing’)
oSocket.close()

print(’[*] Done’)

In line 13 I configure the socksocket to use Tor as a SOCKS5 proxy (Tor needs to be running).

From that line on, the code is the same as for the build-in socket module:

import socket


print(’[*] Creating socket’)
oSocket = socket.socket()


In this first example I build an HTTP GET request, that is something that doesn’t have to be done when module requests is used:

import requests

PROXYHOST = ‘localhost’
PROXYPORT = 9050

HOST = ‘duskgytldkxiuqc6.onion’

url = ‘http://’ + HOST
print(’[*] Requesting %s’ % url)
print(requests.get(url, proxies={‘http’: ‘socks5h://%s:%s’ % (PROXYHOST, PROXYPORT), ‘https’: ‘socks5h://%s:%s’ % (PROXYHOST, PROXYPORT)}).text)

print(’[*] Done’)

Quickpost info

Article Link: https://blog.didierstevens.com/2018/02/03/quickpost-code-to-connect-to-tor-onion-service/