3

I'm creating some firewall rules for a VPS using iptables. My shell script looks something like this:

#!/bin/sh
# My system IP/set ip address of server
SERVER_IP="1.2.3.4"

# Flushing all existing rules
iptables -F
iptables -X

# Setting default filter policy
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

# Allow SSH on 22
iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

# Default policy DROP
iptables -A INPUT -j DROP
iptables -A OUTPUT -j DROP

If i run the iptables -F command after running this script I get locked out of SSH (I can get back in, but I never want the SSH to go down).

I have three questions.

  1. Am I being locked out by the default filter policies not being removed when I run the iptables -F command?
  2. Will I not get locked out if I do iptables -FX?
  3. Are the default filter policies even necessary if I'm adding the default drop policy at the end of the shell script anyway?

Cheers!

1
  • If you want to run a script like that you should put a trap '' EXIT and trap '' SIGHUP in their at the top. It will make the script run to completion even if you kill your connection.
    – Zoredache
    Jul 9, 2012 at 17:31

2 Answers 2

5

Of course you're getting locked out -- you're setting the policy to default deny and then flushing all the rules that let you in.

  1. Yes.
  2. No, because -X has as much to do with chain policy as -F (that is, nothing).
  3. Yes, because rules can be deleted, flushed, spindled, and mutilated. Chain policies cannot.
1
  • Thanks, I thought so. Can you help with the other questions?
    – Nick Pyett
    Jul 9, 2012 at 12:38
1

You should only find ssh locked out temporarily because you have allowed "ESTABLISHED" in the rules. However, the temporary packet loss will upset ssh and it make take 10 seconds or more for tcp to recover.

Myself, I always put in a generic "iptables -A INPUT -m state --state established,related" rule at the top immediately after the flush command so that the lockout is very short!

you're not using conntrack to flush states as well are you?

p.s. if you're controlling connections from a relatively trusted lan then using a REJECT rule at the end can be more helpful as new connection attempts which fail get rejected immediately rather than have to time out.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .