Files
emailwiz/lib/firewall.sh
T

59 lines
1.7 KiB
Bash

# emailwiz - optional UFW rules for the mail ports (TCP only, never SSH)
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
firewall_ports() {
_ports="25 465 587 993"
case " $IMAP_PROTOCOLS " in *" pop3 "*) _ports="$_ports 995" ;; esac
[ "$TLS_MODE" = certbot ] && _ports="$_ports 80"
printf '%s\n' "$_ports"
}
ufw_active() {
have ufw && ufw status 2>/dev/null | head -1 | grep -q '^Status: active'
}
# Ports without an IPv4 ALLOW rule (a "25" any-protocol rule counts as covering 25/tcp).
firewall_missing() {
_st=$(ufw status 2>/dev/null | grep -v '(v6)')
_miss=
for _p in $(firewall_ports); do
printf '%s\n' "$_st" | grep -Eq "^$_p(/tcp)?[[:space:]]+ALLOW" || _miss="$_miss $_p"
done
printf '%s\n' "${_miss# }"
}
# Add a plan note when UFW would block mail ports (read-only).
firewall_note() {
ufw_active || return 0
_m=$(firewall_missing)
[ -z "$_m" ] || note "UFW is active and does not allow tcp port(s): $_m (run: sudo emailwiz firewall)"
}
cmd_firewall() {
need_root firewall
MODE=apply
_yes=no
[ "${1:-}" = --yes ] && _yes=yes
detect_os
config_load
config_validate
if ! ufw_active; then
info "UFW is not active; nothing to do. Mail needs these TCP ports open in any"
info "firewall in front of this host: $(firewall_ports)"
return 0
fi
_m=$(firewall_missing)
[ -n "$_m" ] || { ok "UFW already allows tcp: $(firewall_ports)"; return 0; }
log "UFW will allow tcp: $_m (SSH rules and default policies are not touched)"
if [ "$_yes" != yes ] && ! confirm "Add these UFW rules?" SETUP_UFW; then
warn "skipped; mail ports stay closed in UFW"
return 0
fi
for _p in $_m; do
ufw allow "$_p/tcp" comment emailwiz >/dev/null
info "allowed $_p/tcp"
done
ok "UFW rules added"
}