Skip to content

Instantly share code, notes, and snippets.

@jkullick
Last active November 5, 2024 10:40
Show Gist options
  • Save jkullick/62695266273608a968d0d7d03a2c4185 to your computer and use it in GitHub Desktop.
Save jkullick/62695266273608a968d0d7d03a2c4185 to your computer and use it in GitHub Desktop.
Block Tor Exit Nodes with IPTables
  1. Install ipset:
apt-get install ipset
  1. Create new ipset:
ipset create tor iphash
  1. Read Tor Exit Node List and add to ipset:
curl -sSL "https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=$(curl icanhazip.com)" | sed '/^#/d' | while read IP; do
  ipset -q -A tor $IP
done

Note: This should run as daily cronjob.

  1. Block ipset with iptables:
iptables -A INPUT -m set --match-set tor src -j DROP

Source

@Alkanov
Copy link

Alkanov commented Apr 22, 2020

Here I send you this virtual beer 🍺 because this just saved my life

@MarcosT96
Copy link

In addition to this excellent tool, I want to leave a similar one that has more tor IP addresses, which was also useful for me.

ipset create tor-nodes iphash

curl -sSL "https://www.dan.me.uk/torlist/?ip=$(curl icanhazip.com)" | sed '/^#/d' | while read IP; do
  ipset -q -A tor-nodes $IP
done

iptables -A INPUT -m set --match-set tor-nodes src -j DROP

@mtheofy
Copy link

mtheofy commented Nov 9, 2020

The list from dan.me.uk contains IPv4 and IPv6 addresses. To filter out v6 addresses you can use something like:

ipset create tor-nodes iphash

curl -sSL "https://www.dan.me.uk/torlist/?ip=$(curl icanhazip.com)" | sed -e '/^#/d' -e '/:/d' | while read IP; do
ipset -q -A tor-nodes $IP
done

@avijc
Copy link

avijc commented Jan 2, 2021

@MarcosT96, according to https://www.dan.me.uk/tornodes the URL does not take an "ip" parameter. The only parameter is ?exit, which will list exit nodes only (which is likely what most people want anyway).

@mtheophy, surely we are interested in IPv6 as well :) Many servers have IPv6 nowadays. I grab the list to a temporary file and then grep the IP addresses I'm interested in. For IPv4 I use grep -E "^([0-9]+\.){3}[0-9]+$" and for IPv6 I use grep -E "^[23]...:" (IPv6 regex matching is a complex topic, but this suffices for me for now) and then use it to populate the ipv6-tor-nodes set.

ipset create ipv6-tor-nodes iphash family inet6
ip6tables -A INPUT -m set --match-set ipv6-tor-nodes src -j DROP

@erhan-
Copy link

erhan- commented Mar 6, 2021

@devnulldevzero
Copy link

ipset -N tor iphash
curl 'https://check.torproject.org/torbulkexitlist?ip=' | xargs -n 1 ipset -A tor 
iptables -A INPUT -m set --match-set tor src -j DROP

My version

@zouppen
Copy link

zouppen commented Nov 10, 2022

I made a version with systemd timer and deployment instructions: https://gist.github.com/zouppen/bc005e0038860164714f0cdf376369b4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment