Commit aa676e6f authored by Volodymyr Melnyk's avatar Volodymyr Melnyk
Browse files

Merge branch 'v.melnik-main-patch-62467' into 'main'

Update smtp_filter.sh

See merge request !1
parents f4338f38 7fa4265e
#!/bin/bash
PATH=/bin:/sbin:/usr/bin
top_pid="${$}"
log_file="/var/log/smtp_filter.log"
exit_status_error=42
trap "exit ${exit_status_error}" TERM
function log {
local output
case "${1}" in
1)
exec 3>&1
;;
2)
exec 3>&2
;;
*)
exec 3>/dev/null
;;
esac
shift
echo "[$(date +%F\ %T)]" $* | tee -a "${log_file}" >&3
}
function warn {
log 2 "[!]" $*
}
function die {
warn $*
kill -s TERM "${top_pid}"
}
vms=$(
curl -f -s https://secure.tucha.ua/smtp-filter/banned |
sed -r -n 's/^\s*(i-[[:digit:]]+-[[:digit:]]+-VM)\s*(#.*)$/\1/gp'
)
declare -A vms_ifs
declare -A ifs_vms
for vm in ${vms}; do
ifnames=$(
virsh dumpxml "${vm}" \
| xpath '/domain/devices/interface[@type="bridge"]/target/@dev' 2>&1 \
| sed -r -n 's/^\s*dev="(.+)".*$/\1/gp'
)
vms_ifs["${vm}"]="${ifnames}"
for ifname in ${ifnames}; do
ifs_vms["${ifname}"]="${vm}"
rule_number=$(
ebtables -L FORWARD --Ln \
| sed -r -n 's/^\s*([0-9]+)\.\s+-p\s+IPv4\s+-i\s+'"${ifname}"'\s+--ip-proto\s+tcp\s+-j\s+PORT_LIMIT_'"${vm}"'$/\1/gp'
)
if [[ -z "${rule_number}" ]]; then
ebtables -L "PORT_LIMIT_${vm}" >/dev/null 2>&1
if [[ $? -eq 255 ]]; then
log 1 "Creating an ebtables chain for ${vm}"
ebtables -N "PORT_LIMIT_${vm}"
ebtables -A "PORT_LIMIT_${vm}" -p ipv4 --ip-prot tcp --ip-dport 25 -j DROP
ebtables -A "PORT_LIMIT_${vm}" -p ipv4 --ip-prot tcp -j ACCEPT
fi
log 1 "Adding an ebtables rule for ${vm}"
ebtables -A FORWARD -i "${ifname}" -p ipv4 --ip-prot tcp -j "PORT_LIMIT_${vm}"
fi
done
done
while :; do
deleted=0
for rule in $(
ebtables -L FORWARD --Ln \
| sed -r -n 's/^\s*([0-9])+\.\s+-p\s+IPv4\s+-i\s+(vnet[0-9]+)\s+--ip-proto\s+tcp\s+-j\s+PORT_LIMIT_(i-[0-9]+-[0-9]+-VM)$/\1:\2:\3/gp'
); do
IFS=':' read -r -a rule_elements <<< "${rule}"
not_found=0
if [[ -z "${ifs_vms[${rule_elements[1]}]}" ]]; then ((not_found++)); fi
if [[ -z "${vms_ifs[${rule_elements[2]}]}" ]]; then ((not_found++)); fi
if [[ ${not_found} -gt 0 ]]; then
log 1 \
"Removing the ebtables rule #${rule_elements[0]}, " \
"as the ${rule_elements[2]} VM doesn't seem to be connected " \
"to the ${rule_elements[1]} interface anymore"
ebtables -D FORWARD "${rule_elements[0]}"
ebtables -X "PORT_LIMIT_${rule_elements[2]}"
((deleted++))
break
fi
done
if [[ ${deleted} -eq 0 ]]; then break; fi
done
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment