How to configure CentOS Iptables without getting locked out

I wouldn't be trying to run them by pasting them into the terminal. I'd scp them over and run them from a single script (could just be a bash script with them all pasted in.

With just around the amount of data you have there, i've had situations where pasting that into an ssh terminal has actually led to some loss of data (as in a couple of lines are missed). in something like this, that really isn't such a good idea. Obviously the likelyhood of that happening depends on the link quality and bandwidth.

Also if you're playing around with iptables and are afraid you might lock yourself out, set up a script to clear iptables (or set them to something you're happy works) and then set either a cron job to execute it, or have another window open while you're applying the rules and just do "sleep 100 && ./cleariptables" or something to that affect. Ctrl+c it when new rules have been successful and you're sure you can still log in. Always attempt to make a new ssh connection has you may have blocked new ssh connections and the current one is only working as it's already established


Try moving the /sbin/iptables -P INPUT DROP to the end of the file. If that doesn't work then save the rules to a file and then use the iptables-restore command.

sudo iptables-restore </file/you/created

Once you've done that save your rules to /etc/sysconfig/iptables

sudo /sbin/service iptables save

so that they get loaded when your system starts next.

If the iptables-restore doesn't work then saving the rules manually to /etc/sysconfig/iptables and restarting the service will work

sudo /sbin/service iptables restart

The input file to iptables-restore might be

*filter
-F
-X
-Z
-P INPUT DROP
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p tcp ! --syn -j REJECT --reject-with tcp-reset
-A INPUT -m state --state INVALID -j DROP
# Add the rest of your INPUT/OUTPUT/FORWARD rules before the commit
COMMIT
*mangle 
-X
-F
-Z
-P PREROUTING ACCEPT
#Add the rest of the mangle rules
COMMIT
*nat
-X
#add the rest of your nat rules
COMMIT

Another way not to get locked out is to load your new rules, sleep for x seconds and test during the sleep, then load the old rules that worked in case your new rules don't work.

# load_new_rules; sleep 120; load_old_rules

Good way to not lock yourself out when working on a remote firewall that you don't have remote console access to.


On another linux box, configure via console all the iptables rules and policies. Save it to a file using iptables-save. Copy the file to your remote machine, and apply using:

iptables-apply -t 300 name-of-file

the 300 is the timeout. iptables-apply will apply all rules in the file, wait for your confirmation, and if no confirmation in 300 seconds, restores the previous rules and policies.