You are here: Home / Debian GNU/Linux / System / Security / Filter the access to a network port with iptables on Debian

Filter the access to a network port with iptables on Debian

by Pierre-Yves Landuré last modified Nov 11, 2017 09:37

This howto propose a simple way to filter selectively the access to some ports of a Debian server.

This howto is tested on:

  • Debian 7.0 Wheezy

Parameters

Provide the number of the port to protect:

PORT="3306"

Provide the protocol of the port to protect:

PROTOCOL="tcp"

Provide the IP addresses allowed access to the protected port (one by line):

ALLOWED_IPS="xx.xx.xx.xx
xx.xx.xx.xx
"

Installation

Compute the configuration filename:

CONFIG_FILE="/etc/network/if-up.d/firewall-${PROTOCOL}-${PORT}"

Protection initialization

Block the access to the protected port:

if [ ! -e "${CONFIG_FILE}" ]; then
command echo "#"\!"/bin/bash

# Block new connections to ${PROTOCOL} port ${PORT}:
command iptables -C INPUT -p ${PROTOCOL} -m state --state NEW --dport ${PORT} -j DROP > '/dev/null' 2>&1 \\
|| command iptables -A INPUT -p ${PROTOCOL} -m state --state NEW --dport ${PORT} -j DROP" \
  > "${CONFIG_FILE}"
command chmod +x "${CONFIG_FILE}"
fi

Allowed IPs white list

Open the port for allowed IPs:

for ALLOWED_IP in ${ALLOWED_IPS}; do
  if [ -z "$(command grep "${ALLOWED_IP}" "${CONFIG_FILE}")" ]; then
    command echo "
# Allow access for IP ${ALLOWED_IP}
command iptables -C INPUT -s '${ALLOWED_IP}' -p '${PROTOCOL}' --dport ${PORT} -j ACCEPT > '/dev/null' 2>&1 \\
  || command iptables -I INPUT -s '${ALLOWED_IP}' -p '${PROTOCOL}' --dport ${PORT} -j ACCEPT" \
    >> "${CONFIG_FILE}"
  fi
done

Load the new access rules:

"${CONFIG_FILE}"

The rules defined in ${CONFIG_FILE} file will be loaded during each system startup.