Hardening port security with Iptables
Defending sensitive services using custom verification chains.
Iptables is the primary command-line tool for managing the Netfilter firewall in Linux. It enables granular traffic filtering based on specific criteria. Implementing protection against port scanning involves establishing a "whitelist" of trusted IP addresses for restricted services.
Core concepts
Efficient firewall management relies on three key elements:
- Table: A group of functional chains (the
filtertable is active by default). - Chain: A sequence of rules that packets must pass through (e.g.,
INPUTfor incoming traffic). - Rule: A set of conditions and an action. If a packet matches the criteria, an action such as
ACCEPTorDROPis executed.
Implementing a custom "antiscan" chain
Creating a dedicated antiscan chain is a best practice for centralized access management. This keeps specific service restrictions separate from the main INPUT chain.
1. Create the custom chain:
iptables -N antiscan
2. Whitelist trusted IP addresses: Add the specific IP addresses permitted to access restricted ports.
# Replace with actual trusted administrative or office IPs
iptables -A antiscan -s 1.1.1.1 -j ACCEPT
iptables -A antiscan -s 2.2.2.2 -j ACCEPT
3. Deny all other traffic: The final rule in the chain ensures that unauthorized IPs are blocked.
iptables -N antiscan
4. Route specific port traffic to the Antiscan chain: Traffic targeting sensitive ports is redirected to the custom chain for verification.
For TCP ports (e.g., Databases, Mail servers, Control panels):
iptables -I INPUT -p tcp --match multiport --dports 25,3306,8083 -j antiscan
For UDP ports (e.g., SNMP, RPC):
iptables -I INPUT -p udp --match multiport --dports 111,161 -j antiscan
Making rules persistent
Standard Iptables configurations are volatile and will clear upon reboot. To ensure persistence:
Debian / Ubuntu
iptables-save > /etc/iptables.rules
# Create a network startup script
echo -e '#!/bin/bash\niptables-restore < /etc/iptables.rules' > /etc/network/if-pre-up.d/iptablesup
chmod +x /etc/network/if-pre-up.d/iptablesup
Tip
Installing the iptables-persistent package is recommended for automated management.
Critical considerations
- Rule order: rules are processed sequentially from top to bottom. Once a match occurs, the system stops checking subsequent rules.
- SSH connectivity: ensure the SSH port (default 22) is not inadvertently blocked to prevent loss of remote access.
- Testing: connectivity should be verified from both a whitelisted IP and an external IP to confirm the firewall logic.
Help
If you have any questions or need assistance, please contact us through the ticket system — we're always here to help!