Komplexität ist weder gut noch schlecht. Schlecht ist es, Komplexes kompliziert zu machen, gut ist es, mit Komplexität einfach umzugehen.

Georg Wilhelm Exler (Persönlichkeitscoach)

blocking countries via IP-Tables

blocking countries via IP-Tables

Just improved a small snipped to use on my own server. Its blocks incoming Traffic from all over the world, keeping the door open for requests from Germany. Use it if you want to.

#!/bin/sh
### Restrict all countries and allow traffic from listed countries only
### This example allows IPs from Germany (de) only
###
### author anonymous, improved by MeErWissen, Sven Hering (2021)
###
### used CIDR-list:
###
### IPDENY.COM: "Powered by IPDENY.COM IP database."
### https://www.ipdeny.com/copyright.php
###

### Use ISO code separated by space ###
ISO="de"

### Set PATHs ###
IPT=/sbin/iptables
WGET=/usr/bin/wget
EGREP=/bin/egrep

### No editing below ###
ACCEPTLIST="countryok"
ZONEROOT="/tmp/iptables-country"
# 2021-10-19 -> HTTPS has to be diasbled because the certificate is invalid atm
#DLROOT="https://www.ipdeny.com/ipblocks/data/aggregated"
DLROOT="http://www.ipdeny.com/ipblocks/data/aggregated"
cleanOldRules(){
  $IPT -w -F $ACCEPTLIST
  $IPT -w -D INPUT -j $ACCEPTLIST
  $IPT -w -X $ACCEPTLIST
}

# create a dir
[ ! -d $ZONEROOT ] && /bin/mkdir -p $ZONEROOT

# clean old rules
cleanOldRules

# create a new iptables list
$IPT -N $ACCEPTLIST

# Basic assumptions

# Keep localhost open
$IPT -w -A $ACCEPTLIST -s 127.0.0.1/8 -j RETURN

# Keep local nets open
$IPT -w -A $ACCEPTLIST -s 10.0.0.1/8 -j RETURN
$IPT -w -A $ACCEPTLIST -s 172.16.0.0/12 -j RETURN
$IPT -w -A $ACCEPTLIST -s 192.168.0.1/16 -j RETURN

# Allow SSH (fail2ban is recommended)
$IPT -A $ACCEPTLIST -p tcp -m tcp --dport 22 -j RETURN

for c in $ISO
do
# local zone file
tDB=$ZONEROOT/$c.zone

# get fresh zone file into .tmp
$WGET -O $tDB.tmp $DLROOT/$c-aggregated.zone -o /dev/null || exit 1

# sort list by CIDR (unnecessary just for optical reasons)
sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 $tDB.tmp > $tDB

#remove .temp
rm $tDB.tmp

# count lines for information only, remove next 2 lines for a silent script
lcount=`wc -l < $tDB`

echo Inserting $lcount CIDRs \($c\), stay tuned...

# get each line
GOODCIDRs=$(egrep -v "^#|^$" $tDB)
for CIDRaccept in $GOODCIDRs
do
$IPT -w -A $ACCEPTLIST -s $CIDRaccept -j RETURN
done
done

# country specific log message
DROPMSG='DROP (outside '$ISO') '

# Log and Drop everything else
$IPT -w -A $ACCEPTLIST -j LOG --log-prefix "$DROPMSG"
$IPT -w -A $ACCEPTLIST -j DROP

# Insert chain in INPUT
$IPT -I INPUT -j $ACCEPTLIST

exit 0

sources: https://forums.centos.org, the origin might be https://forum.archive.openwrt.org

Zurück zur Übersicht
RustDesk Logo
Fernwartung
PANDA Sign
DIE ANTIVIRUS REVOLUTION
Watchguard Sign
Intelligente Sicherheit leicht gemacht.

Next Generation VoIP
Sophos Sign
Security made simple
1&1 Shop
Telekom Shop