5

How can I block all ports except:

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

using iptables and ipchains?

Rob Bednark
  • 173
  • 1
  • 5
  • 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 Jun 15 '10 at 15:37
  • Unbelievable that the better thread at https://superuser.com/questions/769814/how-to-block-all-ports-except-80-443-with-iptables is marked as a duplicate for this... – Brian Topping Nov 22 '18 at 17:33

3 Answers3

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
Glorfindel
  • 4,089
  • 8
  • 24
  • 37
3h4x
  • 216
  • 1
  • 4
  • 11
    I ran this script on my server and locked myself out :) – jbasko Apr 23 '12 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 May 28 '12 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 Nov 05 '14 at 03: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 Dec 22 '14 at 18:25
8

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
Dennis Williamson
  • 106,229
  • 19
  • 167
  • 187
askvictor
  • 1,658
  • 4
  • 21
  • 36
  • This is a worthwhile option but consider providing instructions on how to block all incoming traffic except ssh and http, please. – Jeremy W May 30 '12 at 03:48
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

laurent
  • 5,979
  • 17
  • 47
  • 71