linux - How to block all ports except 80,443 with iptables?
2014-07
This question already has an answer here:
First the ! is the NOT symbol.
iptables -A INPUT -p tcp -m tcp -m multiport ! --dports 80,443 -j DROP
Second, the rules you wrote may not have the expected results. You drop everything including the response to the connection on port 80. Therefore, you will not be able to connect to it says for the purposes of a web server.
These rules allow RELATED and ESTABLISHED connections so a web server should function, if that is in fact what your trying to do.
iptables -A INPUT -p tcp -m tcp -m multiport --dports 80,443 -j ACCEPT
<insert further allowed list here>
iptables -A INPUT -m conntrack -j ACCEPT --ctstate RELATED,ESTABLISHED
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -j DROP
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -j DROP
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -j DROP
# Set the default policy of the INPUT chain to DROP
iptables -P INPUT DROP
# Accept incomming TCP connections from eth0 on port 80 and 443
iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 443 -j ACCEPT
This should give you what you need
You can set your default action to DROP, and then create exception rules to allow 80 and 443, like so:
# Setting default policies:
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Exceptions to default policy
iptables -A INPUT -p tcp --dport 80 -j ACCEPT # HTTP
iptables -A INPUT -p tcp --dport 443 -j ACCEPT # HTTPS
iptables will go through the list of 'exceptions' until it finds a match. It will then perform the action specified by the -j
parameter (ACCEPT in this case). If it doesn't find a match, it will fall back to the default policy and drop the packet.
How can I block all ports except
- ssh (port 22)
- httpd (port 80)
using iptables and iphains?
Ipchains are old and i do not reccomend it
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
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