SyntaxStudy
Sign Up
Linux / Bash Firewall Management with ufw and iptables
Linux / Bash Beginner 1 min read

Firewall Management with ufw and iptables

Linux firewalls are implemented through the kernel netfilter framework. Rules are managed at a low level by `iptables` (for IPv4) and `ip6tables` (for IPv6), which provide granular control over packet filtering, NAT, and connection tracking. However, `iptables` syntax is complex, so most systems use a higher-level management tool. UFW (Uncomplicated Firewall) is the default firewall management tool on Ubuntu. It provides a simple syntax for common use cases: allowing or denying ports and services, rate-limiting connections to prevent brute-force attacks, and setting default policies. Behind the scenes it generates `iptables` rules. The `ufw status verbose` command shows all active rules. On Red Hat-based systems, `firewalld` is the standard, managed through the `firewall-cmd` utility. It uses a zone-based model where interfaces are assigned to zones with different trust levels. For cloud instances, security groups (AWS, GCP, Azure) typically serve as the primary firewall layer, though host-based firewalls add defence-in-depth.
Example
# ---- UFW (Ubuntu/Debian) ----

# Check UFW status
sudo ufw status
sudo ufw status verbose
sudo ufw status numbered

# Enable / disable UFW
sudo ufw enable
sudo ufw disable

# Set default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow common services
sudo ufw allow ssh               # Port 22
sudo ufw allow http              # Port 80
sudo ufw allow https             # Port 443
sudo ufw allow 8080/tcp

# Allow from specific IP
sudo ufw allow from 192.168.1.0/24

# Allow from specific IP to specific port
sudo ufw allow from 10.0.0.5 to any port 5432

# Deny a port
sudo ufw deny 23/tcp

# Rate-limit SSH (block after 6 connections in 30s)
sudo ufw limit ssh

# Delete a rule by number
sudo ufw delete 3

# ---- iptables basics ----

# List all rules
sudo iptables -L -v -n

# Allow established connections
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow SSH
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Drop all other inbound traffic
sudo iptables -P INPUT DROP

# Save rules (Debian/Ubuntu)
sudo netfilter-persistent save

# ---- firewalld (RHEL/Fedora) ----
sudo firewall-cmd --state
sudo firewall-cmd --list-all
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload