-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathufw_ban_cidrs.sh
executable file
·103 lines (90 loc) · 2.52 KB
/
ufw_ban_cidrs.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/bin/sh
# This script reads the CIDRs.txt file and,
# line-by-line, each CIDR is banned using ufw.
# Each banned CIDR is prepended as a DENY IN rule.
# Additionally, a comment is added.
# ------------------------------------------------
# Written by Matteo Salonia (matteo@salonia.it)
# Assign flags
F_HELP=0 # Print help
F_IPV6=0 # Ban IPv6 CIDRs
F_DRY_RUN=0 # Dry run
F_FLAGS=0 # Print flags
F_SKIP=0 # Skip checking if the rule already exists
F_SILENT=0 # Do not print 'skipping (already inserted)' messages
[[ $@ =~ "-h" || $@ =~ "--help" ]] && F_HELP=1
[[ $@ =~ "-6" || $@ =~ "--ipv6" ]] && F_IPV6=1
[[ $@ =~ "-d" || $@ =~ "--dry-run" ]] && F_DRY_RUN=1
[[ $@ =~ "-f" || $@ =~ "--flags" ]] && F_FLAGS=1
[[ $@ =~ "-k" || $@ =~ "--skip" ]] && F_SKIP=1
[[ $@ =~ "-s" || $@ =~ "--silent" ]] && F_SILENT=1
# Print usage and exit
if [ $F_HELP = 1 ]; then
printf "Usage: $0 [options]
-h,--help Display this help message
-6,--ipv6 Ban IPv6 CIDRs from CIDRs6.txt (default: IPv4)
-d,--dry-run Do not run ufw; only show which CIDRs would be banned
-f,--flags Print flags and exit
-k,--skip Skip checking if the rule already exists
-s,--silent Do not print 'Skipping (already inserted)' messages
If this is a new installation/empty ruleset, -k/--skip is recommended.
"
exit 0
fi
# Print flags and exit
if [ $F_FLAGS = 1 ]; then
printf "Flags:
F_HELP=$F_HELP
F_IPV6=$F_IPV6
F_DRY_RUN=$F_DRY_RUN
F_FLAGS=$F_FLAGS
F_SKIP=$F_SKIP
F_SILENT=$F_SILENT
"
exit 0
fi
# Get this directory's path
DIRNAME=$(dirname "$0")
# Where our CIDRs file is stored
if [ $F_IPV6 = 0 ]; then
CIDRS_FILE="$DIRNAME/CIDRs.txt"
else
CIDRS_FILE="$DIRNAME/CIDRs6.txt"
fi
# Check if file exists
if ! [ -e "$CIDRS_FILE" ]; then
echo "Cannot find file $CIDRS_FILE!"
exit 1
fi
# Check if we are root
if [ $(whoami) = "root" ]; then
root=""
elif [ $(which doas) ]; then
root="doas"
else
root="sudo"
fi
# Read file
while IFS= read -r line; do
# Split CIDR & Comment
cidr=$(echo $line | awk '{print $1}')
comment=$(echo $line | awk '{print $2}')
# Check if CIDR is already added
if [ $F_SKIP = 0 ]; then
$root ufw status | grep "$cidr" >/dev/null 2>&1
exit_status=$?
fi
# If CIDR is found, skip re-adding the rule
if [[ $exit_status -eq 0 && $F_SKIP = 0 ]]; then
# Should we echo it?
if [ $F_SILENT = 0 ]; then
echo "Skipping $cidr (already inserted)"
fi
else
echo "CIDR: $cidr ($comment)";
# Dry run: only show what would be added
if [ $F_DRY_RUN = 0 ]; then
$root ufw prepend deny from "$cidr" comment "$comment"
fi
fi
done < "$CIDRS_FILE"