How to Block All But Three Ports in Ubuntu Using Iptables

iptablesUbuntu

How can I block all ports except for 1962, 999, 12020?

One port for SSH and two others for a kind of script. So, it's necessary to allow outgoing on these ports, right?

My iptables:

# Generated by iptables-save v1.4.4 on Sat Feb 25 17:25:21 2012
*mangle
:PREROUTING ACCEPT [643521:136954367]
:INPUT ACCEPT [643521:136954367]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [645723:99904505]
:POSTROUTING ACCEPT [645723:99904505]
COMMIT
# Completed on Sat Feb 25 17:25:21 2012
# Generated by iptables-save v1.4.4 on Sat Feb 25 17:25:21 2012
*filter
:INPUT ACCEPT [643490:136950781]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [645723:99904505]
-A INPUT -p tcp -m tcp --dport 1962 -j ACCEPT 
-A INPUT -p tcp -m tcp --dport 999 -j ACCEPT 
COMMIT
# Completed on Sat Feb 25 17:25:21 2012
# Generated by iptables-save v1.4.4 on Sat Feb 25 17:25:21 2012
*nat
:PREROUTING ACCEPT [5673:734891]
:POSTROUTING ACCEPT [2816:179474]
:OUTPUT ACCEPT [2816:179474]
COMMIT
# Completed on Sat Feb 25 17:25:21 2012

Sorry, but I'm a real newbie when it comes to this stuff and I just want make my server more secure.

Best Answer

At first you should always flush to be sure whats already defined… nothing

iptables -F

Then set the default policy of the INPUT chain to DROP if the end is reached and no rule matched:

iptables -P INPUT DROP

To ensure the loopback is not affacted you should add

iptables -A INPUT -i lo -p all -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

to allow all traffic on the lo-if and every incomming traffic for connections you etablished. After that add every rule you need for your services (don't forget to open ssh if you need it! else you're out):

iptables -A INPUT -p tcp -m tcp --dport 1962 -j ACCEPT 
iptables -A INPUT -p tcp -m tcp --dport 999 -j ACCEPT 
iptables -A INPUT -p tcp -m tcp --dport 12020 -j ACCEPT 

A little trick I do to keep myself and others from accidentally drilling holes into the security I finally add:

iptables -A INPUT -j DROP

This line matches everything for the INPUT chain and the policy should not get anything. advantage of this is even if you add an ACCEPT-rule sometime after initializing your ruleset it will never become checked because everything is droped before. so it ensures you have to keep everything in one place.

For your question the whole thing looks like this in summary:

iptables -F
iptables -P INPUT DROP
iptables -A INPUT -i lo -p all -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 1962 -j ACCEPT 
iptables -A INPUT -p tcp -m tcp --dport 999 -j ACCEPT 
iptables -A INPUT -p tcp -m tcp --dport 12020 -j ACCEPT 
iptables -A INPUT -j DROP