Skip to main content

Firewall

Firewalls are essential for securing Linux systems by controlling network traffic based on defined rules. Linux provides several firewall management tools, including:

  • iptables: The traditional packet filtering framework.
  • nftables: A modern replacement for iptables.
  • firewalld: A user-friendly firewall daemon using nftables/iptables.
  • ufw: A simplified interface for iptables, common in Ubuntu.

Managing Firewalls with iptables​

Installing iptables​

sudo apt update && sudo apt install iptables -y  # Debian/Ubuntu
sudo yum install iptables-services -y # RHEL/CentOS

Basic iptables Commands​

  • View rules:
    sudo iptables -L -v -n
  • Allow SSH:
    sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
  • Block an IP:
    sudo iptables -A INPUT -s 192.168.1.100 -j DROP
  • Save rules:
    sudo iptables-save > /etc/iptables.rules

Managing Firewalls with nftables​

Installing nftables​

sudo apt install nftables -y  # Debian/Ubuntu
sudo yum install nftables -y # RHEL/CentOS

Basic nftables Commands​

  • Start nftables:
    sudo systemctl start nftables
  • Create a rule to allow SSH:
    sudo nft add rule ip filter input tcp dport 22 accept
  • List current rules:
    sudo nft list ruleset
  • Save rules:
    sudo nft list ruleset > /etc/nftables.conf

Managing Firewalls with firewalld​

Installing firewalld​

sudo apt install firewalld -y  # Debian/Ubuntu
sudo yum install firewalld -y # RHEL/CentOS

Basic firewalld Commands​

  • Start and enable firewalld:
    sudo systemctl start firewalld
    sudo systemctl enable firewalld
  • Allow HTTP and HTTPS traffic:
    sudo firewall-cmd --permanent --add-service=http
    sudo firewall-cmd --permanent --add-service=https
    sudo firewall-cmd --reload
  • Block an IP:
    sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" reject'
  • List active rules:
    sudo firewall-cmd --list-all

4. Managing Firewalls with UFW (Uncomplicated Firewall)​

Installing UFW​

sudo apt install ufw -y  # Debian/Ubuntu

Basic UFW Commands​

  • Enable UFW:
    sudo ufw enable
  • Allow SSH:
    sudo ufw allow 22/tcp
  • Deny an IP:
    sudo ufw deny from 192.168.1.100
  • List rules:
    sudo ufw status numbered

Best Practices​

  • Use minimal rules: Keep rules as simple as possible.
  • Limit SSH access: Allow SSH only from trusted IPs.
  • Enable logging: Monitor firewall logs for security insights.
  • Regularly update rules: Review and update rules to reflect current security policies.