iptables
List all running rules
To view the current firewall rules:
iptables -L -v
Disable and flush iptables
To disable the firewall temporarily, flush all rules.
sudo iptables -P INPUT ACCEPT sudo iptables -P OUTPUT ACCEPT sudo iptables -P FORWARD ACCEPT sudo iptables -F
Deny all traffic
To block everything, drop all packets on all chains.
sudo iptables -P INPUT DROP sudo iptables -P OUTPUT DROP sudo iptables -P FORWARD DROP
A common example
Here is a common example to allow SSH, HTTP and HTTPS, but drop everything else.
Step 1
Append a rule to the INPUT chain:
Protocol TCP
Destination port 22, 80 & 443
For those packets, jump to ACCEPT.
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
Step 2
Append a rule to the INPUT chain: Drop everything else.
sudo iptables -A INPUT -j DROP
UFW
Enable UFW with the default set of rules:
sudo ufw enable
View status
Check the status of the server firewall with
sudo ufw status
Disable UFW
sudo ufw disable
Reset UFW to default
sudo ufw reset
Example: Allow SSH, deny all other
A trivial example that blocks all inbound traffic except SSH (port 22).
sudo ufw default deny incoming sudo ufw default allow outgoing sudo ufw allow ssh
Allow connections
If you are running a web server, you want the world to be able to access your website(s). Therefore, you need to make sure that the default TCP ports for web are open.
sudo ufw allow 80/tcp sudo ufw allow 443/tcp
In general, you can allow any port you need by using the following format:
sudo ufw allow /
Deny connections
If you need to deny access to a certain port, use the deny command:
sudo ufw deny /
For example, you can deny access to your default MySQL port:
sudo ufw deny 3306
UFW also supports a simplified syntax for the most common service ports:
sudo ufw deny mysql
Rule updated
Rule updated (v6)