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.
#!/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"
[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.
[Unit]
Description=Run the block tor script every 6 hours
[Timer]
OnBootSec=5min
OnUnitActiveSec=6h
[Install]
WantedBy=timers.target
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:
- Download the Tor exit nodes list.
- Create or update the
ipset
hash namedtor-exit-nodes
. - Add a rule to
iptables
to block all IPs from that list. - Run every 6 hours using
systemd
timer.