How can I block all but three ports in Ubuntu?

Solution 1:

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

Solution 2:

A reply from a newbie just like you :-) I needed to secure my Ubuntu server as well, learning iptables was a pain I could not get through. UFW (Uncomplicated Firewall) is a program to make firewall configuration as easy as possible.

  • install ufw:

    sudo apt-get install ufw
    
  • disable it immediately (I had to rescue-boot because I was locked out of my own SSH login):

    sudo ufw disable
    
  • set "deny" as default rule (this blocks all ports):

    sudo ufw default deny
    
  • allow ports you need:

    sudo ufw allow to 1962
    sudo ufw allow to 999
    sudo ufw allow to 12020
    
    sudo ufw allow from 1962
    sudo ufw allow from 999
    sudo ufw allow from 12020
    
  • if you're certain the rules above do not break your ssh connection, enable ufw:

    sudo ufw enable
    

Docs are well written and provide more examples: https://help.ubuntu.com/community/UFW