Hello Wilfred!
12 Mar 24 16:31, you wrote to me:
Hi Christian,
Next you could filter the netblocks from countries you don't
expect to receive traffic from and add iptables rules to drop the
packets received from them. You can browse to
https://www.ipdeny.com/ipblocks/data/aggregated/ to download the
lists per country.
That's a fast moving target. So you need to update (very) often...
Personally I update in a crontab @reboot and every day
If you're interested I got a python script that can do the job.
Yes thanks! That would be interesting!
Here it is :
-+- snip ---
# -*- coding: utf-8 -*-
import subprocess, logging
COUNTRIES = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,GB, IN, UA, US, EG,SA, RW,NG,ZA, IS"
COUNTRIES = [country.strip().lower() for country in COUNTRIES.split(',')]
FAMILY = "ipv4"
CHAIN = "COUNTRIES"
TARGET = "RETURN"
PRE_RULES = ["-s 10.0.0.0/8 -j RETURN"]
POST_RULES = ["-j LOGIPS", "-j DROP"]
logging.basicConfig(level=logging.INFO)
TEST = """10.0.10.3/32
"""
def run(command, silent=False):
ret = subprocess.call(command, shell=True)
if ret:
logger = logging.warning
elif silent == False:
logger = logging.info
else:
logger = lambda x: None
logger("%s: %s" % (ret, command))
def append_rule(rule):
command = "/usr/sbin/iptables -A %s %s" % (CHAIN, rule)
run(command)
def download(country):
url = "
http://www.ipdeny.com/ipblocks/data/aggregated/%s-aggregated.zone" % country
try:
import urllib.request
logging.debug("retrieving %s" % url)
data = urllib.request.urlopen(url).read().decode('utf-8')
logging.debug("%s: %i lines" % (country, len(data.splitlines())))
return data
except:
try:
import urllib2
data = urllib2.urlopen(url).read()
logging.debug("%s: %i lines" % (country, len(data.splitlines())))
return data
except:
raise
command = "/usr/sbin/iptables -F %s" % CHAIN
run(command)
for rule in PRE_RULES:
command = "/usr/sbin/iptables -A %s %s" % (CHAIN, rule)
run(command)
for country in COUNTRIES:
try:
ipset_name = "%s-%s" % (FAMILY, country)
command = "/usr/sbin/ipset list -terse %s-%s >/dev/null 2>&1 || /usr/sbin/ipset create %s-%s hash:net family %s" % (FAMILY, country, FAMILY, country, FAMILY)
run(command)
ranges = download(country)
for range in ranges.splitlines():
range = range.strip()
if range:
command = "/usr/sbin/ipset -A -exist -quiet %s %s" % (ipset_name, range)
run(command, silent=True)
command = "/usr/sbin/iptables -A %s -p tcp -m set --match-set %s src -j %s" % (CHAIN, ipset_name, TARGET)
run(command)
except:
logging.exception("error while processing %s" % ipset_name)
for rule in POST_RULES:
command = "/usr/sbin/iptables -A %s %s" % (CHAIN, rule)
run(command)
-+- /snip ---
Hope it helps,
Christian
--- GoldED+/LNX 1.1.5--b20170303
* Origin: ----> SPARK BBS (2:292/2226)