💾 Archived View for nox.im › snippets › openbsd-block-country-traffic captured on 2024-08-18 at 18:17:45. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2022-06-03)
-=-=-=-=-=-=-
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[1]. To accomplish this we need to know IP zones which we can get from `ipdeny.com` and use OpenBSD PF[2] (packet filter).
1: setting up an httpd web server
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
- https://undeadly.org/cgi?action=article;sid=20140527054301[1]
1: https://undeadly.org/cgi?action=article;sid=20140527054301
- https://www.openbsd.org/faq/pf/[1]