homemade_firewall/makeconf.sh

51 lines
1.8 KiB
Bash
Executable File

#!/bin/bash
# ${1} is original filename
# ${2} is counter (start at 0)
# ${3} is file to replace from
replace(){
# change newlines to Ñ so we can use it as replacement pattern
local pattern=$(sed ':a;N;$!ba;s/\n/Ñ/g;s/\(\/\|\.\)/\\\1/g' "${3}")
if [ ${2} != "0" ]
# Ñ is changed back to newlines before saving file
then
local new_content="$(sed "1,/^include \"\.\/[a-z]\+\.nft\"$/{s/^include \"\.\/[a-z]\+\.nft\"$/${pattern}/}" "${1}""$(bc -l <<< "${2} - 1")".nft | sed 's/Ñ/\n/g')";
echo "${new_content}" > "${1}${2}".nft
else
local new_content="$(sed "1,/^include \"\.\/[a-z]\+\.nft\"$/{s/^include \"\.\/[a-z]\+\.nft\"$/${pattern}/}" "${1}".nft | sed 's/Ñ/\n/g')";
echo "${new_content}" > "${1}${2}".nft
fi
}
filename=filter
declare -i counter=0
# only replace local files
declare -a local_includes=( $(grep "include \"\./[a-z.]\+\"" filter.nft | awk '{print $2}' | tr -d \"))
for i in ${local_includes[@]}
do replace "${filename}" "${counter}" "${i}"
counter+=1
done
#rename last temp file to nftables.conf
counter=${counter}-1
mv "${filename}""${counter}".nft nftables.conf
counter=${counter}-1
while [ ${counter} -ge 0 ]
#delete the rest of the temp files to nftables.conf
do rm "${filename}""${counter}".nft
counter=${counter}-1
done
# figure out what countries, if any, we're blocking
declare -a countries=($(ls -1 /var/geoipsets/dbip/nftset/ipv4/))
# figure out which line defines the elements of the blacklist set
line="$(grep -nA3 blacklist nftables.conf | grep elements | awk 'BEGIN{FS="-"} {print $1}')"
# insert names of the countries to block into the line that defines the elements of the set
for i in ${countries[@]};
do sed -i "${line} s/elements = { \([A-Z]\{2\}\.ipv4,\? \)*/elements = { \1\$${i}, /" nftables.conf
done
# delete unnecesary last comma
sed -i "${line} s/, }/ }/" nftables.conf