Block all ports except SSH/HTTP in ipchains and iptables

How can I block all ports except:

  1. ssh (port 22)
  2. httpd (port 80)

using iptables and ipchains?


Solution 1:

Which Linux distribution? You may be better off using a higher level firewall like ufw:

As root/sudo:

ufw default deny
ufw allow ssh
ufw allow http
ufw enable

Solution 2:

IP chains are old and I do not recommend them.

A simple script:

#!/bin/bash
IPTABLES=/sbin/iptables

#start and flush
$IPTABLES -F
$IPTABLES -t nat -F
$IPTABLES -X
$IPTABLES -P FORWARD DROP
$IPTABLES -P INPUT   DROP
$IPTABLES -P OUTPUT  ACCEPT

#SSH traffic
$IPTABLES -A INPUT -p tcp --dport 22 -j ACCEPT
#HTTP traffic
$IPTABLES -A INPUT -p tcp --dport 80 -j ACCEPT

#loopback
$IPTABLES -A INPUT -i lo -p all -j ACCEPT

Solution 3:

Using ufw to block everything by default but allow ssh and http/https:

sudo ufw default deny incoming
sudo ufw default deny outgoing
sudo ufw allow 22
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable

Also remember that by default Docker and ufw don't work well together, you'll need to change the Docker daemon config as described there: https://stackoverflow.com/a/49563279/561309