Didier Stevens

Saturday 3 February 2018

Quickpost: Code To Connect To Tor Onion Service

Filed under: Networking,Quickpost — Didier Stevens @ 20:16

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


1 Comment »

  1. Thank you. Good tutorial. Best regards,

    Comment by Cătălin George Feștilă — Tuesday 6 February 2018 @ 21:35


RSS feed for comments on this post. TrackBack URI

Leave a Reply (comments are moderated)

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: