iptables – quick how to block a port (and save it)

If you don’t know what iptables are – don’t bother reading this post.

I had a recent issue with the vncserver on my virtual private server – I don’t use the service and wouldn’t have turned it on, however the hosting provided I acquired the vps from included it in their base build, enabled and listening on both ports 5902 and 5903.  I turned the service off (using ‘chkconfig vncserver off’).  But, ever after that – my server was still responding to ports 5902 and 5903.

Ok – so if its not vncserver – I don’t know what it is.  But ‘netstat -tp’ didn’t reveal anything listening on those ports.  So rather than waste a lot of time trying to figure it out – I figured I would take the easy route and block the port.  This is how I did it:

iptables -A INPUT -p tcp –dport 5902 -j DROP
iptables -A INPUT -p tcp –dport 5903 -j DROP

I derived those commands from here: http://www.linuxforums.org/forum/linux-security/29397-closing-ports.html using input from Goran.

Ok – telnet to those ports no longer responds – great!  But then I rebooted the server (actually I just restarted iptables using ‘service iptables restart’).  Now my server is replying to those ports again.  DOH!

I realized I need to save the firewall rules after I ran them.  I read a lot about exporting and importing the rules using iptables-save and iptables-restore – but this seemed like overkill.  I finally found this: http://www.linuxquestions.org/questions/red-hat-31/how-to-save-iptables-415929/

‘service iptables save’

Volla – worked like a champ!  Hope it helps you!

Leave a Reply