How to block all ports using IPtables

June 26, 2024 / How-to Guide

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:

  1. Connect to the Server
    Log in to the server as the root user using SSH.
  2. Flush Existing IPtables Rules
    Remove any existing rules to avoid conflicts:

    iptables -F
    iptables -X
  3. 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.

  4. Allow Established and Related Connections
    Ensure existing connections continue to work:

    iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
  5. Allow Loopback Traffic
    Allow internal system processes to communicate:

    iptables -A INPUT -i lo -j ACCEPT
    iptables -A OUTPUT -o lo -j ACCEPT
  6. 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
  7. 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
  8. Allow a Range of Ports (Optional)
    To allow a specific port range:

    iptables -A INPUT -p tcp --dport 1024:2000 -j ACCEPT
  9. 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
  10. 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
  11. Save and Apply the Rules
    Save the configuration:

    iptables-save > /etc/sysconfig/iptables
  12. 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.

Spread the love