Skip to content

Instantly share code, notes, and snippets.

@Warchant
Last active March 31, 2024 14:31
Show Gist options
  • Save Warchant/c3c19311ef49435be73919bd68e70e60 to your computer and use it in GitHub Desktop.
Save Warchant/c3c19311ef49435be73919bd68e70e60 to your computer and use it in GitHub Desktop.
Geoip capabilities with iptables/ufw + automatic IP addr db updates
  1. sudo apt install curl perl unzip xtables-addons-common libtext-csv-xs-perl libmoosex-types-netaddr-ip-perl
  2. Put this into /usr/local/bin/geoip-update.sh
#!/bin/bash -e

WORKDIR=`mktemp -d`
if [[ ! "$WORKDIR" || ! -d "$WORKDIR" ]]; then
        echo "Could not create temp dir"
        exit 1
fi

cd $WORKDIR
/usr/libexec/xtables-addons/xt_geoip_dl
/usr/libexec/xtables-addons/xt_geoip_build -s -i dbip*.csv
  1. /etc/systemd/system/geoip-update.service
[Unit]
Description="Rebuilds /usr/share/xt_geoip database"

[Service]
ExecStart=/usr/local/bin/geoip-update.sh
  1. /etc/systemd/system/geoip-update.timer

This tells OS to update geoip database once a week (on Sat 10:00)

[Unit]
Description="Update geoip database"

[Timer]
OnBootSec=5min
OnUnitActiveSec=24h
OnCalendar=Sat *-*-* 10:00:*
Unit=geoip-update.service

[Install]
WantedBy=multi-user.target
  1. modprobe xt_geoip

  2. Add rules to UFW. Prepend before COMMIT (at the very end).

#### CUSTOM EXAMPLE:
# block all traffic from RU,CN
-A ufw-before-input -p tcp -m geoip --src-cc RU,CN -j DROP

# block all traffic to port 22 from all ips except UA
-A ufw-before-input -p tcp --dport 22 -m geoip ! --src-cc UA -j DROP
#### END CUSTOM
  1. sudo systemctl start geoip-update
  2. sudo systemctl enable geoip-update
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment