Security
Configure UFW and iptables to control inbound and outbound traffic on Linux.
▶ Watch the demo: lock down a server with UFW in 4 commands (22 sec)Watch on YouTubeSubscribe
Contents
UFW — Uncomplicated Firewall
UFW is the recommended tool for managing firewall rules on Ubuntu.
# Install and enable
sudo apt install -y ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow specific services
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 2222/tcp # custom SSH port
# Allow a specific IP
sudo ufw allow from 192.168.1.100 to any port 22
# Enable firewall
sudo ufw enable
sudo ufw status verbose
Manage UFW Rules
# List rules with numbers
sudo ufw status numbered
# Delete rule by number
sudo ufw delete 3
# Delete by specification
sudo ufw delete allow 8080/tcp
# Disable UFW
sudo ufw disable
iptables Basics
# List current 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
# Block an IP
sudo iptables -A INPUT -s 203.0.113.5 -j DROP
# Save rules (Ubuntu)
sudo netfilter-persistent save
Rate Limit SSH Connections
Limit SSH connection attempts to block brute-force attacks:
sudo ufw limit ssh/tcp
# Equivalent iptables rule:
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
nftables (Modern Alternative)
sudo apt install -y nftables
sudo systemctl enable --now nftables
# Example ruleset in /etc/nftables.conf
table inet filter {
chain input {
type filter hook input priority 0; policy drop;
ct state established,related accept
tcp dport { ssh, http, https } accept
drop
}
}
Last updated October 2026.