6

How can I block all ports except:

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

using iptables and ipchains?

2
  • While ochach's answer is technically correct, I think you need to clarify your question. Do you mean "block all input except ssh and http"? If you follow ochach's answer, you won't be able to do anything - no data will be allowed out of your box.
    – baumgart
    Commented Jun 15, 2010 at 15:37
  • Unbelievable that the better thread at superuser.com/questions/769814/… is marked as a duplicate for this... Commented Nov 22, 2018 at 17:33

3 Answers 3

9

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
2
  • This is a worthwhile option but consider providing instructions on how to block all incoming traffic except ssh and http, please.
    – Jeremy W
    Commented May 30, 2012 at 3:48
  • with these exact commands I lost the ssh connection and have to reset the firewall settings via the VPS web dashboard
    – xealits
    Commented Jul 6 at 22:04
8

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
4
  • 12
    I ran this script on my server and locked myself out :)
    – jbasko
    Commented Apr 23, 2012 at 22:45
  • 3
    @Zilupe to easily not loose acces to server remember to use cron while editing firewall - like: */2 * * * * iptables -P INPUT ACCEPT
    – 3h4x
    Commented May 28, 2012 at 10:04
  • SSH requires 40 seconds to connect with your rules, against 3 seconds without. I suspect you drop DNS resolution capabilities too.
    – Dereckson
    Commented Nov 5, 2014 at 3:35
  • Missing these 2 lines iptables -A INPUT -m conntrack -m cpu -j ACCEPT --ctstate RELATED,ESTABLISHED iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    – cybernard
    Commented Dec 22, 2014 at 18:25
2

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

You must log in to answer this question.