Block all ports except SSH/HTTP in ipchains and iptables

23,975

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

Share:
23,975

Related videos on Youtube

Rob Bednark
Author by

Rob Bednark

Software Engineer resume LinkedIn Facebook Twitter github:robbednark Google+ Quora PortlandUpside.com email/Hangouts: rbednark (gmail.com) Skype ID: rbednark

Updated on September 17, 2022

Comments

  • Rob Bednark
    Rob Bednark over 1 year

    How can I block all ports except:

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

    using iptables and ipchains?

    • Dustin Holtz
      Dustin Holtz almost 14 years
      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.
    • Brian Topping
      Brian Topping over 5 years
      Unbelievable that the better thread at superuser.com/questions/769814/… is marked as a duplicate for this...
  • rivasket
    rivasket about 12 years
    I ran this script on my server and locked myself out :)
  • 3h4x
    3h4x almost 12 years
    @Zilupe to easily not loose acces to server remember to use cron while editing firewall - like: */2 * * * * iptables -P INPUT ACCEPT
  • Jeremy W
    Jeremy W almost 12 years
    This is a worthwhile option but consider providing instructions on how to block all incoming traffic except ssh and http, please.
  • Dereckson
    Dereckson over 9 years
    SSH requires 40 seconds to connect with your rules, against 3 seconds without. I suspect you drop DNS resolution capabilities too.
  • cybernard
    cybernard over 9 years
    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