Setting up an onion service

Setting up an onion service

What is Tor?

Tor is a protocol that enables anonymous communication over internet by routing traffic through many volunteer operated servers known as relays.
Tor provides anonymity by masking both client’s and the server’s IP addresses.

What is Onion Service?

An Onion Service is a service hosted on the Tor network that is only accessible through the Tor network using a .onion address. These services are designed to provide the anonymity both for the users accessing the service and for the server hosting the service.

Forwarding Tor Traffic to Local Server via Onion Address

Step 1: Setting up Tor Network

Install tor on the machine

sudo apt update
sudo apt install tor

Step 2: Configure tor Hidden Service

We will need to configure Tor to run hidden service

We need to edit /etc/tor/torrc file

Add the following lines in the configuration

 # Setting up hidden service (Onion Service)
HiddenServiceDir /var/lib/tor/hidden_service/
HiddenServicePort 80 127.0.0.1:3000
  • HiddenServiceDir: Tor will store the data of our hidden service in this directory.

  • HiddenServicePort: This tells tor to redirect incoming traffic on port 80 of the .onion address to our local server running on port 3000

Step 3: Restart Tor Service

We will need to restart the Tor service to load the new configuration

sudo systemctl restart tor

Step 4: Retrieve .onion Address

After Tor has restarted, it will create the hidden service files in the directory that we have specified above. In our case it is /var/lib/tor/hidden_service/.

cat /var/lib/tor/hidden_service/hostname

Since it is not safe to share the .onion address of our hidden service publicly, we are going to use examplexyz.onion as our tor onion service url

Step 5: Setup basic Flask Server

Before that, create a virtual environment using

python3 -m venv myenv
source myenv/bin/activate # to activate the environment

Install flask to setup flask server

pip install flask

Create a file server.py and write this script

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return {
        "message": "We are talking from on tor network",
        "status": "success"
    }

if __name__ == '__main__':
    app.run(debug=True, port=3000)

python server.py

Step 6: Looking at the response

Go to the Tor address examplexyz.onion on any device with Tor installed, and you will see a response like this.