How To Allow / Block Ports in Linux Firewall

Managing ports in Linux firewalls is a key step in securing servers and controlling traffic. This guide explains how to allow or block ports using UFW, Firewalld, iptables, and nftables across different Linux distributions.

UFW (Uncomplicated Firewall)

  • Allow a port:
    sudo ufw allow <port>/tcp
    sudo ufw allow 80/tcp
  • Deny a port:
    sudo ufw deny <port>/tcp
    sudo ufw deny 80/tcp
  • List all rules:
    sudo ufw status numbered
  • Reload firewall:
    sudo ufw reload

Firewalld

  • Allow a port:
    sudo firewall-cmd --zone=public --add-port=<port>/tcp --permanent
    sudo firewall-cmd --zone=public --add-port=80/tcp --permanent
  • Deny a port:
    sudo firewall-cmd --zone=public --remove-port=<port>/tcp --permanent
    sudo firewall-cmd --zone=public --remove-port=80/tcp --permanent
  • List all active rules:
    sudo firewall-cmd --list-all
  • Reload firewall:
    sudo firewall-cmd --reload

iptables

  • Allow a port:
    sudo iptables -A INPUT -p tcp --dport <port> -j ACCEPT
    sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
  • Deny a port:
    sudo iptables -A INPUT -p tcp --dport <port> -j DROP
    sudo iptables -A INPUT -p tcp --dport 80 -j DROP
  • List active rules:
    sudo iptables -L -v -n
  • Save rules:
    sudo iptables-save > /etc/iptables/rules.v4
    sudo ip6tables-save > /etc/iptables/rules.v6
  • Restore rules:
    sudo iptables-restore < /etc/iptables/rules.v4
    sudo ip6tables-restore < /etc/iptables/rules.v6

nftables

  • Allow a port:
    sudo nft add rule ip filter input tcp dport <port> accept
    sudo nft add rule ip filter input tcp dport 80 accept
  • Deny a port:
    sudo nft add rule ip filter input tcp dport <port> drop
    sudo nft add rule ip filter input tcp dport 80 drop
  • List rules:
    sudo nft list ruleset
  • Save rules permanently:
    sudo nft list ruleset > /etc/nftables.conf
  • Reload firewall with saved rules:
    sudo nft -f /etc/nftables.conf

Each firewall tool has its own syntax, but the principle remains the same: define rules to allow or block traffic on specific ports. While iptables is widely used, nftables is the modern replacement offering improved performance and flexibility.

By mastering these commands, you can secure your Linux system effectively while ensuring that necessary services remain accessible.

Post a Comment

Previous Post Next Post

Contact Form