This post describe a simple way to block all access to a network port on Debian, except for specified IP addresses.
This howto is tested on:
- Debian 7.0 Wheezy
Settings
Provide the port number to protect:
port='3306'
Provide the protocol for which to protect the port (tcp or udp):
protocol='tcp'
Provide a list of IP addresses allowed access to the protected port:
declare -a allowedIPs
allowedIPs=( 'xx.xx.xx.xx' 'xx.xx.xx.xx' )
Configuration
Detect if sudo is available (“command” is used if not):
cmdProxy='command'
command type -f 'sudo' &>'/dev/null' && cmdProxy='sudo'
Compute the configuration file name:
configFile="/etc/network/if-up.d/firewall-${protocol}-${port}"
Blocking access the port
Block access to the port for everything:
if [ ! -e "${configFile}" ]; then
${cmdProxy} tee "${configFile}" \
<<< "#"\!"/bin/bash
#
# Block new connections to ${protocol} port ${port}:
iptables -C INPUT -p '${protocol}' -m 'state' --state 'NEW' --dport ${port} -j 'DROP' > '/dev/null' 2>&1 \\
|| iptables -A INPUT -p '${protocol}' -m 'state' --state 'NEW' --dport ${port} -j 'DROP'"
${cmdProxy} chmod +x "${configFile}"
fi
Allowing access for specific IPs
Open the port for the allowed IP addresses:
for allowedIP in ${allowedIPs}; do
if ! command grep --quiet "${allowedIP}" "${configFile}"; then
${cmdProxy} tee "${configFile}" \
<<< "
# Allow access for IP ${allowedIP}
iptables -C INPUT -s '${allowedIP}' -p '${protocol}' --dport ${port} -j ACCEPT > '/dev/null' 2>&1 \\
|| iptables -I INPUT -s '${allowedIP}' -p '${protocol}' --dport ${port} -j ACCEPT"
fi
done
Load the access restriction rules:
${cmdProxy} "${configFile}"
All iptables rules written in a executable script stored in “/etc/network/if-up.d” are loaded when network interfaces come up (this include during boot).
0 Comments