This guide explains how to secure a Linux server using IPtables by blocking all ports by default and allowing only the services you explicitly require. This approach helps reduce the server’s attack surface.
Important Warning:
- Always allow SSH access before blocking other ports.
- Applying restrictive firewall rules without allowing SSH may result in permanent loss of server access.
Follow the steps:
- Connect to the Server
Log in to the server as the root user using SSH. - Flush Existing IPtables Rules
Remove any existing rules to avoid conflicts:iptables -F iptables -X
- Set Default Policies
Block all incoming and forwarded traffic while allowing outbound traffic:iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT ACCEPT
Keeping OUTPUT as ACCEPT is recommended to allow DNS resolution, package updates, and external communications.
- Allow Established and Related Connections
Ensure existing connections continue to work:iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
- Allow Loopback Traffic
Allow internal system processes to communicate:iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT
- Allow SSH Access
Allow SSH access to prevent lockout.
Allow SSH from all IPs:iptables -A INPUT -p tcp --dport 22 -j ACCEPT
OR allow SSH from a specific IP:
iptables -A INPUT -p tcp -s YOUR_IP_ADDRESS --dport 22 -j ACCEPT
- Allow Required Service Ports
Example rules for common services:
HTTP and HTTPS:iptables -A INPUT -p tcp --dport 80 -j ACCEPT iptables -A INPUT -p tcp --dport 443 -j ACCEPT
- Allow a Range of Ports (Optional)
To allow a specific port range:iptables -A INPUT -p tcp --dport 1024:2000 -j ACCEPT
- Allow DNS Traffic
Permit DNS queries for proper name resolution:iptables -A OUTPUT -p udp --dport 53 -j ACCEPT iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
- Disable Ping Requests (Optional)
Block outgoing ping:iptables -A OUTPUT -p icmp --icmp-type echo-request -j DROP
Block incoming ping:
iptables -A INPUT -p icmp --icmp-type echo-request -j DROP
- Save and Apply the Rules
Save the configuration:iptables-save > /etc/sysconfig/iptables
- Restart the IPtables service:
service iptables restart
By correctly configuring IPtables and allowing only essential ports, you can significantly improve server security and reduce potential attack vectors. Always review firewall rules carefully before applying them to a live server, as incorrect rules may block access or cause downtime.
Need to block specific IP addresses or domains? Check out our guide on How to Block an IP address or a Domain Name Using cPanel.