Tor logo

Block Tor exit nodes using iptables

Tor logoSo this evening I had to manually block 22 Tor exit nodes because they were running a denial of service attack on my server. Not my idea of a fun start of the weekend.

It turns out that the Tor project has a list of exit nodes that can reach a certain IP-address. Well, I can automate that…

#!/bin/bash

if [[ -z "$1" ]]; then
	echo Usage: $0 "<your host's ip>"
	exit 1
fi

hostip=$1

for i in $(wget https://check.torproject.org/cgi-bin/TorBulkExitList.py\?ip=$hostip -O- -q |\
		grep -E '^[[:digit:]]+(\.[[:digit:]]+){3}$'); do
	sudo iptables -A INPUT -s "$i" -j DROP
done

So now that server is blocking 700-ish Tor exit nodes. And I have a handy little script standing by to drop in at a moment’s notice to do the same task anywhere else.

Update 17 March 2015: the script is also downloadable on GitHub.