Networking · #16 of 19
Firewall Basics
ufw & iptables
What is a Firewall?
A firewall filters network traffic based on rules:
- Allow: Let traffic through
- Deny: Block silently
- Reject: Block and notify sender
Linux has a powerful firewall (iptables/nftables) built into the kernel. ufw (Uncomplicated Firewall) makes it easier to use.
ufw — Simple Firewall
Check Status
sudo ufw status # Status and rules
sudo ufw status verbose # More details
sudo ufw status numbered # Rules with numbers
Enable/Disable
sudo ufw enable # Turn on firewall
sudo ufw disable # Turn off firewall
sudo ufw reset # Reset to defaults
Basic Rules
Allow Traffic
sudo ufw allow 22 # Allow SSH (port 22)
sudo ufw allow ssh # Same thing (by service name)
sudo ufw allow 80/tcp # Allow HTTP (TCP only)
sudo ufw allow 443 # Allow HTTPS
sudo ufw allow 6000:6007/tcp # Allow port range
Deny Traffic
sudo ufw deny 23 # Block telnet
sudo ufw deny from 10.0.0.1 # Block specific IP
Delete Rules
sudo ufw status numbered # See rule numbers
sudo ufw delete 2 # Delete rule #2
sudo ufw delete allow 80 # Delete by specification
Common Scenarios
Web Server
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
Database Server (Internal Only)
sudo ufw allow from 192.168.1.0/24 to any port 3306
sudo ufw deny 3306
Development Machine
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw enable
Advanced Rules
Limit Connections (Brute-Force Protection)
sudo ufw limit ssh # Max 6 connections per 30 sec
Specific Interface
sudo ufw allow in on eth0 to any port 80
Specific IP Range
sudo ufw allow from 192.168.1.0/24 to any port 22
Logging
sudo ufw logging on # Enable logging
sudo ufw logging medium # Set log level
tail -f /var/log/ufw.log # View logs
Default Policies
sudo ufw default deny incoming # Block all incoming
sudo ufw default allow outgoing # Allow all outgoing
sudo ufw default deny routed # Block forwarded traffic
Recommended defaults:
- Deny incoming (whitelist what you need)
- Allow outgoing (you initiated it)
iptables (Advanced)
ufw is a frontend for iptables. Direct iptables is more powerful but complex:
# View current rules
sudo iptables -L -n -v
# Allow SSH
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Block IP
sudo iptables -A INPUT -s 10.0.0.1 -j DROP
# Save rules
sudo iptables-save > /etc/iptables/rules.v4
Modern systems are moving to nftables, which replaces iptables.
Application Profiles
ufw knows about common applications:
sudo ufw app list # See available profiles
sudo ufw app info OpenSSH # Details about profile
sudo ufw allow "Nginx Full" # Allow Nginx HTTP+HTTPS
Try It!
Practice firewall commands in the terminal:
Exercises:
- Check status:
ufw status - List app profiles:
ufw app list - See what SSH rule looks like:
ufw show added
Try it in the terminal
A sandboxed shell with this lesson’s commands. Type help to see what’s available.