Skip to content

Instantly share code, notes, and snippets.

@meetnick
Created September 4, 2024 23:25
Show Gist options
  • Save meetnick/24f8204398c835d439e9c5c6147bdcdc to your computer and use it in GitHub Desktop.
Save meetnick/24f8204398c835d439e9c5c6147bdcdc to your computer and use it in GitHub Desktop.
Block Tor exit nodes using systemd

Here’s a shell script that pulls all Tor exit nodes and blocks them using iptables. The script will create an ipset hash for blocking the Tor exit nodes, and you can set up a systemd service and timer to run it periodically.

1. Shell Script: block_tor_exit_nodes.sh

#!/bin/bash

# Name of the ipset list
IPSET_NAME="tor-exit-nodes"

# URL to pull the list of Tor exit nodes
TOR_EXIT_NODES_URL="https://check.torproject.org/torbulkexitlist"

# Create ipset list if not already exists
if ! ipset list "$IPSET_NAME" >/dev/null 2>&1; then
    echo "Creating ipset list $IPSET_NAME"
    ipset create "$IPSET_NAME" hash:ip
fi

# Flush the ipset list to ensure we only have fresh IPs
ipset flush "$IPSET_NAME"

# Fetch the list of Tor exit nodes
TOR_EXIT_NODES=$(curl -s "$TOR_EXIT_NODES_URL")

# Add each Tor exit node to the ipset list
for IP in $TOR_EXIT_NODES; do
    ipset add "$IPSET_NAME" "$IP"
done

# Ensure iptables rule is in place to block the ipset list
if ! iptables -C INPUT -m set --match-set "$IPSET_NAME" src -j DROP 2>/dev/null; then
    echo "Adding iptables rule to drop traffic from $IPSET_NAME"
    iptables -I INPUT -m set --match-set "$IPSET_NAME" src -j DROP
fi

echo "Tor exit nodes updated and blocked"

2. Create the systemd service: /etc/systemd/system/block-tor.service

[Unit]
Description=Block Tor exit nodes by updating ipset
After=network.target

[Service]
ExecStart=/path/to/block_tor_exit_nodes.sh
ExecReload=/path/to/block_tor_exit_nodes.sh
ExecStop=/sbin/ipset destroy tor-exit-nodes
RemainAfterExit=true

Make sure to replace /path/to/block_tor_exit_nodes.sh with the actual path of the script.

3. Create the systemd timer: /etc/systemd/system/block-tor.timer

[Unit]
Description=Run the block tor script every 6 hours

[Timer]
OnBootSec=5min
OnUnitActiveSec=6h

[Install]
WantedBy=timers.target

4. Enable and start the service and timer

To enable and start the service and timer:

sudo systemctl enable block-tor.service
sudo systemctl start block-tor.service

sudo systemctl enable block-tor.timer
sudo systemctl start block-tor.timer

This setup will:

  1. Download the Tor exit nodes list.
  2. Create or update the ipset hash named tor-exit-nodes.
  3. Add a rule to iptables to block all IPs from that list.
  4. Run every 6 hours using systemd timer.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment