1

I always get nervous when editing iptables as I know how simple it can be to end up blocking all traffic to the server, a rather large issue when your server is sitting on the cloud.

Would these be the correct series of commands?

iptables -A INPUT -p tcp --dport 123 -s 1.2.3.4 -j ACCEPT 
iptables -A INPUT -p tcp --dport 123 -s 5.6.7.8 -j ACCEPT
iptables -A INPUT -p tcp --dport 123 -j DROP
iptables-save
Bart De Vos
  • 17,911
  • 6
  • 63
  • 82
The Digital Ninja
  • 764
  • 4
  • 10
  • 25
  • I guess you should also add the corresponding settings for the OUTPUT chain, to make sure that connections in the reverse direction are only to the allowed IPs from the allowed ports. Like iptables -A OUTPUT -p tcp --sport 123 -d 1.2.3.4 -j ACCEPT. And of course the corresponding DROP line. – Isaac Feb 05 '13 at 17:19

3 Answers3

5

This doesn't answer your question - others are doing a nice job of that - but it does address your other concern: locking yourself out of your remote server. Whenever I'm doing a big iptables change on a system, I always check that atd is running, then put an at job for about 10 minutes in the future to take the firewall down, something like

at now + 10 minutes
at> service iptables stop
at> ^D

That way I know that if I really foul up and lock myself out, in ten minutes' time I'll be able to get back in and fix things. If I finish my work, and I haven't fouled up, I can find that job with atq and delete it with atrm before it even runs.

MadHatter
  • 79,770
  • 20
  • 184
  • 232
2

It should work, but it can be improved. You haven't posted what your default INPUT policy is. If it is ACCEPT, then your commands should work, although not the most recommended one. If it is DROP, then you don't need the line before iptables-save.

The most recommended policy for iptables, as well as for any other firewall, is to DROP EVERYTHING and then explicitly allow the ports/protocols you want to permit. So you start with this -

iptables -A INPUT -j DROP

Then you explicitly allow the incoming traffic destined to port 123/tcp

iptables -A INPUT -p tcp --dport 123 -s 1.2.3.4 -j ACCEPT

iptables -A INPUT -p tcp --dport 123 -s 5.6.7.8 -j ACCEPT

Daniel t.
  • 9,291
  • 1
  • 33
  • 36
  • If you want to drop everything "else", set a default policy. In particular, if iptables commands are executed in above order, you will have a problem. – Bittrance Feb 05 '13 at 17:28
  • I Agree. At the beginning you set the default policies for INPUT, OUTPUT, FORWARD and then explicitly open up the ports/protocols you need. – Daniel t. Feb 05 '13 at 17:30
0

In debian iptables package there is '/usr/sbin/iptables-apply' who ask you if all are ok after apply changes, if you do not repply the question then chages are undone.

Brigo
  • 1,534
  • 11
  • 8