Linux - Setting up a firewall in Linux
Setting up a firewall in Linux depends on your distribution and the tool you prefer to use. Below is a step-by-step guide for the two most common firewall tools: UFW (Uncomplicated Firewall) for Ubuntu/Debian systems and firewalld for Red Hat-based systems. I’ll also touch on iptables for advanced users.
1. Using UFW (Uncomplicated Firewall) – Ubuntu/Debian
Step 1: Install UFW (if not already installed)
sudo apt install ufw
Step 2: Enable UFW
sudo ufw enable
Step 3: Set Default Policies
Block all incoming traffic and allow outgoing traffic:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Step 4: Allow Specific Services or Ports
Allow SSH (port 22):
sudo ufw allow ssh
Allow HTTP (port 80) and HTTPS (port 443):
sudo ufw allow 80
sudo ufw allow 443
Step 5: Check Status
sudo ufw status verbose
Step 6: Disable UFW (if needed)
sudo ufw disable
2. Using firewalld – Red Hat, Fedora, CentOS
Step 1: Install firewalld
sudo dnf install firewalld
Step 2: Start and Enable firewalld
sudo systemctl start firewalld
sudo systemctl enable firewalld
Step 3: Check Default Zone
sudo firewall-cmd --get-default-zone
Step 4: Allow Services
Allow SSH:
sudo firewall-cmd --zone=public --add-service=ssh --permanent
Allow HTTP and HTTPS:
sudo firewall-cmd --zone=public --add-service=http --permanent
sudo firewall-cmd --zone=public --add-service=https --permanent
Step 5: Reload to Apply Changes
sudo firewall-cmd --reload
Step 6: List Active Rules
sudo firewall-cmd --list-all
3. Using iptables – Advanced Control
Step 1: View Current Rules
sudo iptables -L -v
Step 2: Set Default Policies
sudo iptables -P INPUT DROP
sudo iptables -P OUTPUT ACCEPT
sudo iptables -P FORWARD DROP
Step 3: Allow Specific Traffic
Allow SSH:
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Allow HTTP:
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
Step 4: Save Rules
On Debian/Ubuntu:
sudo apt install iptables-persistent
sudo netfilter-persistent save
On Red Hat:
sudo service iptables save
Final Tips
- Always test your rules before applying them permanently.
- Keep SSH access open to avoid locking yourself out.
- Use logging to monitor dropped packets:
sudo iptables -A INPUT -j LOG --log-prefix "IPTables-Dropped: "