This posts explains how to block incoming tor connection using iptables and ipset. The first step is to obtain the tor exit nodes list, it could be downloaded from the https://opendbl.net/.
wget https://opendbl.net/lists/tor-exit.list
The second step is to install ipset and ipset-persistent packages and create an ipset list named torlist in which the tor exit nodes will be inserted using a small bash script.
apt install ipset ipset-persistent
ipset create torlist hash:ip
This script read list downloaded line by line check the validity of each IP address and insert it in the ipset list torlist that has been just created., finally the ipset list is saved in the file /etc/iptables/ipsets.
#!/bin/bash
while IFS= read -r ip; do
[[ -z "$ip" || "$ip" =~ ^# || "$ip" ! =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] && continue
ipset add torlist $ip -exist
done < "tor-exit.list"
ipset save > /etc/iptables/ipsets
The last step is to create an INPUT iptables rule placed as the first rule to drop the incoming Tor connections.
iptables -I INPUT 1 -m set --match-set torlist src -j DROP
iptables-save > /etc/iptables/rules.v4