Last active
December 3, 2024 00:46
-
-
Save siavash119/49ba9921fa860735eaa8c7cdbdc39ed6 to your computer and use it in GitHub Desktop.
firehol sets to nftables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
trust="{1.1.1.1/32, 1.0.0.1/32, 8.8.8.8/32, 114.114.114.114/32, 114.114.115.115/32}" | |
declare -A sets | |
#sets["firehol2"]="https://iplists.firehol.org/files/firehol_level2.netset" | |
sets["blocklist_net_ua"]="https://iplists.firehol.org/files/blocklist_net_ua.ipset" | |
sets["firehol3"]="https://iplists.firehol.org/files/firehol_level3.netset" | |
table_name="sink" | |
rule_file="/etc/nft/rules.d/10_firehol_rules.nft" | |
function mytrap() { | |
echo "deleting netset files" | |
for key in ${!sets[@]}; do | |
rm "/tmp/${key}_IPs.netset" | |
done | |
} | |
trap "mytrap" INT TERM EXIT | |
echo "downloading ip sets" | |
for key in ${!sets[@]}; do | |
echo ${key} ${sets[${key}]} | |
curl --retry-all-errors --retry 5 -s "${sets[${key}]}" | sed -r -e '/^#/d' -e '/^\s*$/d' -e 's/^/\t\t\t/' -e '$!s/$/,/' > "/tmp/${key}_IPs.netset" & | |
done | |
wait | |
sync | |
declare -A ips | |
for key in ${!sets[@]}; do | |
ips[${key}]=`cat /tmp/"${key}_IPs.netset"` | |
if [[ ${ips[${key}]} == "" ]]; then | |
echo "error downloading ${key} set. exiting" | |
exit 1 | |
fi | |
done | |
echo "writing nftables script to $rule_file" | |
touch "$rule_file" | |
rm "$rule_file" | |
#header | |
cat <<HERE > "$rule_file" | |
#!/sbin/nft -f | |
table inet $table_name | |
delete table inet $table_name | |
table inet $table_name { | |
counter blackhole { } | |
HERE | |
#set elements | |
for key in ${!sets[@]}; do | |
cat <<HERE >> "$rule_file" | |
set ${key} { | |
type ipv4_addr; flags constant, interval; | |
elements = { | |
${ips["${key}"]} | |
} | |
} | |
HERE | |
done | |
#chain | |
cat <<HERE >> "$rule_file" | |
chain ${table_name}_chain { | |
type filter hook input priority -300; policy accept; | |
ip saddr $trust accept | |
ip daddr $trust accept | |
HERE | |
for key in ${!sets[@]}; do | |
cat <<HERE >> "$rule_file" | |
#ip saddr @${key} counter name "blackhole" log prefix "nftables ${key} source dropped:" drop | |
#ip daddr @${key} counter name "blackhole" log prefix "nftables ${key} destination dropped:" drop | |
ip saddr @${key} counter name "blackhole" drop | |
ip daddr @${key} counter name "blackhole" drop | |
HERE | |
done | |
cat <<HERE >> "$rule_file" | |
accept | |
} | |
} | |
HERE | |
chmod u+x "$rule_file" | |
/sbin/nft -c -f "$rule_file" > /dev/null 2>&1 | |
exit $? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for your version, here is my improved version of the script