block-badips-ipset
#139
by
doekia
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/bin/bash
# cron.hourly script to block ip signaled on badips.com
# Despite been a cron.hourly, the cron can be limited to at will frequency
#
# Copyright (c)2020 doekia Enter-Solutions GPL
#
# Fetch the https://www.badips.com/get/list
# and block ip nodes listed there.
# Ignore/whitelist googlebot address
#
# uncomment this line to change frequency behaviour
# it is a list of valid hour to update the set - e.g. 0 5 10 15 20 = every 5 hours
RUNON='0 5 10 15 20'
service='any'
level=3
timeout=86400
age='2d'
##############################################
whitelist='
127.0.0.0/8
10.0.0.0/8
172.16.0.0/12
192.168.0.0/16
#googlebot
209.185.0.0/16
209.85.128.0/17
216.239.32.0/19
216.32.0.0/14
64.233.160.0/19
64.68.64.0/19
66.249.64.0/19
72.14.192.0/18
8.0.0.0/9
#letsencrypt
66.133.109.36
64.78.149.164
18.196.17.13
18.216.110.187
18.219.177.57
3.120.126.223
54.202.29.69
34.222.229.130
52.15.254.228
'
if [ "$1" != "forced" -a "$RUNON" != "" ]; then
# Check the time to limit on whishes
H=$(date +%H)
T=$(echo "$RUNON" | egrep "^$H | $H | $H$|^$H$")
if [ "$RUNON" != "$T" ]; then
exit 0;
fi
fi
PID=$$
if [ ! -z "${age}" ]; then age="?age=${age}"; fi
if [ ! -z "${timeout}" ]; then timeout=" timeout ${timeout}"; fi
# Create the set if it does not exists
if ! ipset -q -L badips >/dev/null 2>&1; then
ipset create badips hash:ip timeout 604800 maxelem 1048576
iptables -I INPUT -m set --match-set badips src -j DROP
fi
_url="https://www.badips.com/get/list/${service}/${level}{$age}"
# Get the bad IPs and store in an array
_badips=( $( wget -qO- ${_url} ) ) || { echo "$0: Unable to download ip list from \'${_url}\'." >&2; exit 1; }
# Prevent localip to be ban (just after a hacking been fixed)
localips=$(ip address show | grep -e 'inet ' -e 'inet6 ' | sed -e 's/.*inet6* \([^ ]*\) .*$/\1/g')
whitelist="
${whitelist}
${localips}
"
for _ip in ${_badips[@]}; do
_ip=${_ip##*ff:}
grepcidr "${whitelist}" <(echo ${_ip}) 2>/dev/null && \
continue || \
ipset add badips ${_ip} -exist ${timeout} >/dev/null 2>&1
done