← Back to home
iptables firewalld Firewall UFW Linux

Firewall with iptables & firewalld

Feb 25, 2022

Practical firewall configuration on Linux with iptables, UFW and firewalld, covering default policies, filtering rules and NAT.

1. Default Policy β€” Deny All

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT

2. Common Rules

iptables -A INPUT -p tcp --dport 22 -j ACCEPT   # SSH
iptables -A INPUT -p tcp --dport 80 -j ACCEPT   # HTTP
iptables -A INPUT -p tcp --dport 443 -j ACCEPT  # HTTPS
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT  # Ping
iptables -A INPUT -s 192.168.1.100 -j DROP      # Block specific IP

3. NAT

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
echo 1 > /proc/sys/net/ipv4/ip_forward

4. Save Rules

iptables-save > /etc/iptables/rules.v4
apt install iptables-persistent && netfilter-persistent save

5. UFW (Simplified)

ufw enable
ufw default deny incoming && ufw default allow outgoing
ufw allow ssh && ufw allow http && ufw allow https
ufw status verbose

6. firewalld (CentOS/RHEL)

firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --reload