GITLAB

Snippets

Sign in
  • Sign in

Block torexit node with iptables + ipset
Add new snippet


#76 by 72f60816e60779e1cff35b00d383cb94?s=40&d=identicon doekia
← discover snippets
block-torexit-ipset Buy Me a Coffee at ko-fi.com
raw
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#!/bin/bash
# cron.hourly script to block tor exit node 
# Despite been a cron.hourly, the cron can be limited to a different frequency - see RUNON
#
# Copyright (c)2017 doekia Enter-Solutions GPL
#
# Fetch the https://check.torproject.org/cgi-bin/TorBulkExitList.py
# and block ip nodes listed there.
#

# uncomment this line to change frequency behaviour
# it is a list of valid hour to update the set - e.g. 0 8 16 = every 8 hours
#RUNON='0 8 16'


##############################################
if [ "$RUNON" != "" ]; then
	# Check the time to limit on whishes
	H=$(date +%H)
	T=$(echo "$RUNON" | egrep "^$H | $H | $H$|^$H$")
	if [ "$RUNON" != "$T" ]; then
  		exit 0;
	fi
fi

PID=$$

# Create the set if it does not exists
if ! ipset -q -L tor >/dev/null 2>&1; then
	ipset -N tor iphash
	iptables -I INPUT -m set --match-set tor src -j DROP
fi

# Fetch the torexit list
wget -q 'https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=1.1.1.1' -O - | sed '/^#/d' | sort -u > /tmp/$PID.tor.txt
# Recover the set list
ipset -L tor | grep -E '^[[:digit:]]+(\.[[:digit:]]+){3}$' | sort -u > /tmp/$PID.set.txt


# find the recent torexit node and add them to the set
for node in $(comm -2 -3 /tmp/$PID.tor.txt /tmp/$PID.set.txt); do
	ipset -q -A tor $node
done

# remove those not longer torexit node from the set
for node in $(comm -1 -3 /tmp/$PID.tor.txt /tmp/$PID.set.txt); do
	ipset -q -D tor $node
done

rm /tmp/$PID.tor.txt /tmp/$PID.set.txt