Skip to content

4.2.6 Ensure ufw firewall rules exist for all open ports

Audit#

Run the following script to verify a firewall rule exists for all open ports:

#!/usr/bin/env bash
{
unset a_ufwout;unset a_openports
while read -r l_ufwport; do
[ -n "$l_ufwport" ] && a_ufwout+=("$l_ufwport")
done < <(ufw status verbose | grep -Po '^\h*\d+\b' | sort -u)
while read -r l_openport; do
[ -n "$l_openport" ] && a_openports+=("$l_openport")
done < <(ss -tuln | awk '($5!~/%lo:/ && $5!~/127.0.0.1:/ && $5!~/\[?::1\]?:/) {split($5, a, ":"); print a[2]}' | sort -u)
a_diff=("$(printf '%s\n' "${a_openports[@]}" "${a_ufwout[@]}"
"${a_ufwout[@]}" | sort | uniq -u)")
if [[ -n "${a_diff[*]}" ]]; then
echo -e "\n- Audit Result:\n ** FAIL **\n- The following port(s) don't have a rule in UFW: $(printf '%s\n' \\n"${a_diff[*]}")\n- End List"
else
echo -e "\n - Audit Passed -\n- All open ports have a rule in UFW\n"
fi
}

Remediation#

For each port identified in the audit which does not have a firewall rule, evaluate the service listening on the port and add a rule for accepting or denying inbound connections in accordance with local site policy: Examples:

# ufw allow in <port>/<tcp or udp protocol>
# ufw deny in <port>/<tcp or udp protocol>

Note: Examples create rules for from any, to any. More specific rules should be concentered when allowing inbound traffic e.g only traffic from this network. Example to allow traffic on port 443 using the tcp protocol from the 192.168.1.0 network:

ufw allow from 192.168.1.0/24 to any proto tcp port 443