0

My goal is to shut down absolutely all ports on my Ubuntu server, except port 22 (SSH).

I followed the instructions from this question here on Server Fault, plus instructions here and here.

However, after going through the instructions, it seems like my ports are still open. Here's port 80, for example:

$ nmap -p 80 ###.###.###.###

Starting Nmap 5.21 ( http://nmap.org ) at 2012-05-09 15:36 JST
Nmap scan report for ###-###-###-###.name.name.com (###.###.###.###)
Host is up (0.0065s latency).
PORT   STATE SERVICE
80/tcp open  http

Nmap done: 1 IP address (1 host up) scanned in 1.63 seconds

Here is the contents of my iptables:

# sudo iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination         
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh 
ACCEPT     all  --  anywhere             anywhere            
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED 
DROP       all  --  anywhere             anywhere            

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Just looking at it, especialy where it says "Accept all anywhere", it seems like I have the opposite of what I want. It looks like instead of closing down ports, I've opened them up. However, these are the results of following the instructions to the letter, so maybe I just don't understand what the terms really mean.

In any case, bottom line, what do I do to shut down all ports except 22, and then make it stick even if the server gets rebooted. Surely it's just a few commands at the command line?

(Please note I'm a web designer who got this task, so I'm not at all a super confident server admin. Please make answers easy to understand. Thanks!)

Questioner
  • 127
  • 1
  • 8

1 Answers1

5

As you expected the line:

ACCEPT     all  --  anywhere             anywhere            

means all protocols/ports are allowed since it comes before this line:

DROP       all  --  anywhere             anywhere            

You are not denying any port since there is only one DROP rule that comes after an ACCEPT rule which is allowing everything.

iptables rules are matched in order, so you need to have the following rules if you want to allow only port 22 to be allowed on INPUT chain:

iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

The above two rules should be enough with default INPUT policy set to DROP as indicated in the line:

Chain INPUT (policy DROP)

To make your rule-set persistent, you can use iptables-save > rules_file to dump your rule-set to a text file. Then, it can be loaded during server startup by including it in any script using iptables-restore.

Khaled
  • 35,688
  • 8
  • 69
  • 98