Firewall Configuration
Configure iptables and ufw to protect your systems.
Firewalls reduce your attack surface by controlling which traffic is allowed in/out. The safest mindset is default deny inbound, then explicitly allow what you need (SSH, HTTP/HTTPS, etc.).
UFW (Uncomplicated Firewall)
On Ubuntu/Debian servers, UFW is an easy front-end to iptables/nftables. The safe sequence is: allow SSH first โ set default policies โ then enable.
$ sudo ufw default deny incoming
$ sudo ufw default allow outgoing
# Allow SSH before enabling (avoid lockout)
$ sudo ufw allow OpenSSH
$ sudo ufw limit 22/tcp # Rate limit brute-force
# Allow web traffic
$ sudo ufw allow 80,443/tcp # Allow HTTP/HTTPS
$ sudo ufw deny 3306 # Block MySQL
$ sudo ufw enable
$ sudo ufw status verbose
$ sudo ufw status numbered
Need to remove a rule? Use numbered status and delete by index:
$ sudo ufw delete 1
iptables Basics
iptables is the classic interface. Many modern distros use nftables underneath, but iptables commands may still work via compatibility layers.
In production, prefer a managed approach (UFW/firewalld) unless you need custom rules.
$ iptables -A INPUT -p tcp --dport 22 -j ACCEPT
$ iptables -A INPUT -j DROP # Default deny
Minimal inbound policy (conceptual)
A typical server allows: loopback, established connections, SSH, and optionally HTTP/HTTPS. Everything else is dropped.
$ iptables -P INPUT DROP
$ iptables -A INPUT -i lo -j ACCEPT
$ iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
$ iptables -A INPUT -p tcp --dport 22 -j ACCEPT
$ iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
Persisting rules
iptables rules are often not persistent across reboot unless you save them (e.g., iptables-persistent/netfilter-persistent on Debian/Ubuntu).
$ sudo iptables-save > /etc/iptables/rules.v4
Verify from the outside
Always confirm firewall behavior from a different machine (or at least a different terminal session).
$ nc -vz server.example.com 443
โ Practice (20 minutes)
- Enable UFW with default deny inbound and allow only SSH + HTTP/HTTPS.
- Verify open ports using
ss -tulpnlocally andnc -vzfrom another machine. - Remove a UFW rule using
ufw status numbered+ufw delete.