What this does is allow you to easily work with iptables without the fear of ever being locked out of a remote box. Trust me, when it happens, you’ll wish you had something like this.

All you really would need to change to use this yourself is the FLUSH_WAIT timer and maybe some of the print’s. Otherwise, this should work across pretty much all systems.

Read the comments to learn more about what this does. Enjoy!

# setup for easy management of iptables function ipt { if [[ "$1" == "clear" ]]; then print -P "\e[95mFlushing firewall and allowing everyone...\n" sudo iptables -F sudo iptables -X sudo iptables -t nat -F sudo iptables -t nat -X sudo iptables -t mangle -F sudo iptables -t mangle -X sudo iptables -P INPUT ACCEPT sudo iptables -P FORWARD ACCEPT sudo iptables -P OUTPUT ACCEPT print -P "\e[0;32mDone!" elif [ -e "$1" ]; then # Here we setup a fall back where we flush the rules if the user locks themselves out! # The first sleep is to allow time for the rules to be loaded, the second is the wait. # We expect them to ^C out of this if everything is fine. if [ -n "$TMUX" -o -n "$STY" ]; then # checking for presence in a virtual terminal FLUSHWAIT=10 print -P "\e[95mImporting rules into kernel...\e[0m\n" sudo iptables-restore < "$1" sleep 1s print -P "\e[0;33mIf you can see this, *push ^C*, if not, flushing rules in $FLUSHWAIT seconds.\n" sleep $FLUSH_WAIT $0 clear else print -P "\e[0;91mYou are not in a virtual terminal (e.g. screen or tmux)! Please enter one before importing iptables rules (for your own safety)." fi else print -P "Usage: $0 [clear (flush all rules, allow all!) | (provide file to load into iptables]\nNote your sudo timer (by default 5m) must be longer than the time we wait to flush rules if something happens or else we wont be able to clear out the firewall if you get locked out!\nThis script can be used withOUT being root!" fi }

Blog Logo

Mario Loria


Published

Image

./scriptthe.net

Because 127.0.0.1 gets old after a while.

Back to Overview