nox.im ยท 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 ipdeny.com 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 ipdeny.com for both IPv4 and IPv6, example for ru tr cn in pk ng:

#!/bin/sh

PFDIR=/etc/pf-files
ZONEFILE=blocked_zones
ZONEFILE6=blocked_zones6

mkdir -p ${PFDIR}
> ${PFDIR}/${ZONEFILE}
> ${PFDIR}/${ZONEFILE6}

for ZONE in ru tr cn in pk ng
do
    ftp -o - http://ipdeny.com/ipblocks/data/countries/${ZONE}.zone >> ${PFDIR}/${ZONEFILE}
    ftp -o - http://ipdeny.com/ipv6/ipaddresses/aggregated/${ZONE}-aggregated.zone >> ${PFDIR}/${ZONEFILE6}
    sleep 1 #respect ipdeny policies
done

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

References


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