ยท All Snippets

OpenBSD Block Country Traffic

For whatever reason we may have, there are situations where we want to block traffic from a country or IP zone. For example, after setting up an httpd web server. To accomplish this we need to know IP zones which we can get from and use OpenBSD PF (packet filter).

doas mkdir /etc/pf-files
touch /etc/pf-files/blocked_zones
touch /etc/pf-files/blocked_zones6

In /etc/pf.conf the following needs to be added, in the prerequisites-section add:

table <blocked_zones> persist file "/etc/pf-files/blocked_zones"
table <blocked_zones> persist file "/etc/pf-files/blocked_zones6"

In the block-section add early:

block in quick proto tcp from <blocked_zones> to any port { 22 80 443 }
block in quick proto tcp from <blocked_zones6> to any port { 22 80 443 }

Test the config

pfctl -vnf /etc/pf.conf

if good, reload the config

pfctl -f /etc/pf.conf

Then use a script to pull the zones from for both IPv4 and IPv6, example for ru tr cn in pk ng:



mkdir -p ${PFDIR}

for ZONE in ru tr cn in pk ng
    ftp -o -${ZONE}.zone >> ${PFDIR}/${ZONEFILE}
    ftp -o -${ZONE} >> ${PFDIR}/${ZONEFILE6}
    sleep 1 #respect ipdeny policies

pfctl -t blocked_zones -T replace `cat ${PFDIR}/${ZONEFILE}`

I’ve moved this script to /usr/local/bin/blockzones and set up a crontab as root with crontab -e to run at 08:01 on Mondays. The file is locate in /var/cron/tabs/root.

1 8 * * 1 /usr/local/bin/blockzones


Last modified on Thursday, Dec 30, 2021.
Go back