Friday, June 15, 2018

Iptables, allow common ports, block the rest


I want to allow people to connect to ports 22, 80, and 443. Also I want to be able to do DNS lookups from my server.


Here's what I'm trying:


iptables -A INPUT -m tcp -p tcp --dport 1 -j ACCEPT
iptables -A INPUT -m udp -p udp --dport 1 -j ACCEPT
iptables -A INPUT -m tcp -p tcp --dport 53 -j ACCEPT
iptables -A INPUT -m udp -p udp --dport 53 -j ACCEPT
iptables -A INPUT -m tcp -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -m udp -p udp --dport 80 -j ACCEPT
iptables -A INPUT -m tcp -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -m udp -p udp --dport 443 -j ACCEPT
iptables -A INPUT -m tcp -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -m udp -p udp --dport 22 -j ACCEPT
iptables -A INPUT -m tcp -p tcp -j REJECT
iptables -A INPUT -m udp -p udp -j REJECT
iptables -A OUTPUT -m tcp -p tcp -j ACCEPT
iptables -A OUTPUT -m udp -p udp -j ACCEPT

iptables -L


Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT tcp -- anywhere anywhere tcp dpt:tcpmux
ACCEPT udp -- anywhere anywhere udp dpt:1
ACCEPT tcp -- anywhere anywhere tcp dpt:domain
ACCEPT udp -- anywhere anywhere udp dpt:domain
ACCEPT tcp -- anywhere anywhere tcp dpt:http
ACCEPT udp -- anywhere anywhere udp dpt:http
ACCEPT tcp -- anywhere anywhere tcp dpt:https
ACCEPT udp -- anywhere anywhere udp dpt:https
ACCEPT tcp -- anywhere anywhere tcp dpt:ssh
ACCEPT udp -- anywhere anywhere udp dpt:ssh
REJECT tcp -- anywhere anywhere tcp reject-with icmp-port-unreachable
REJECT udp -- anywhere anywhere udp reject-with icmp-port-unreachable
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
ACCEPT tcp -- anywhere anywhere tcp
ACCEPT udp -- anywhere anywhere udp

If I omit these lines:


iptables -A INPUT -m tcp -p tcp -j REJECT
iptables -A INPUT -m udp -p udp -j REJECT

I can ping out, but then I'm not closing all ports by default, which is the goal. Why is an INPUT rule affecting my ability to do hostname lookups (ex "ping google.com" from my server?)


Answer



You need to allow related traffic back in again (i.e: the replies to your outgoing DNS traffic). Also, you may want to use a default drop rather than a specific deny-all rule to save some space.


iptables -A INPUT -p tcp -m multiport --dports 22,80,443 -j ACCEPT


iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT


iptables -P INPUT DROP


Your OUTPUT chain rules aren't needed as the chain has a default ACCEPT on it currently, and the port 53 rules aren't needed because you aren't hosting a DNS server, merely using one, so the traffic leaves via the OUTPUT chain, not the INPUT one.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...