-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinstall-rules-ipset.sh
executable file
·88 lines (70 loc) · 2.16 KB
/
install-rules-ipset.sh
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
countries=$( cat countries.txt )
date=$(date --iso-8601)
echo "making backup of iptables..."
# you can always restore your rules via iptables-restore in case something goes wrong...
mkdir -p backups
iptables-save > backups/$date-iptables.save
xz backups/$date-iptables.save
# note: you first have to have called ./fetch-ripe-assignments.sh
# this creates the data/*.txt files with lists of CIDR ranges.
# next, iterate over these:
for cc in $countries; do
ipset="${cc}-blocker"
ipv4file="data/$date-$cc-ipv4.txt"
ipset destroy $ipset
ipset create $ipset hash:net counters
# ################### IPv4
echo "Installing new netblock rules for country $cc."
echo "==============================================="
echo "(IPv4)"
echo
let i=0
for netblock in $(bzcat $ipv4file.bz2 | sort | uniq | iprange --optimize ); do
ipset -exist add $ipset $netblock
result=$((i++ % 100))
if [ $result -eq 0 ]; then
echo -n "."
fi
done
echo "Done (v4)"
# ################### IPv6
ipset6="${cc}-blocker-v6"
ipv6file="data/$date-$cc-ipv6.txt"
ipset destroy $ipset6
ipset create $ipset6 hash:net family inet6 counters
echo
echo "(IPv6)"
echo
let i=0
for netblock in $(bzcat $ipv6file.bz2 | sort | uniq ); do
ipset add $ipset6 $netblock
result=$((i++ % 100))
if [ $result -eq 0 ]; then
echo -n "."
fi
done
echo "done (v6)"
# activate the rules, here is where the magic of ipset comes in... It ends up being two rules only for many CIDR ranges.
iptables -I INPUT -m set --match-set $ipset src -j DROP
ip6tables -I INPUT -m set --match-set $ipset6 src -j DROP
done
## Now do the extra-ranges.txt
ipset="extra-blocker"
ipset destroy $ipset
ipset create $ipset hash:net counters
ipv4file="extra-ranges.txt"
echo "Installing new netblock rules for all extra ranges"
echo "=================================================="
echo "(IPv4)"
echo
let i=0
for netblock in $(cat $ipv4file | sort | uniq | iprange --optimize ); do
ipset -exist add $ipset $netblock
result=$((i++ % 100))
if [ $result -eq 0 ]; then
echo -n "."
fi
done
iptables -I INPUT -m set --match-set $ipset src -j DROP
echo "Done (v4)"