Skip to content

Instantly share code, notes, and snippets.

@InAnimaTe
Created October 1, 2019 14:50
Show Gist options
  • Save InAnimaTe/ee004d4a9b804cb73785519df6b0682c to your computer and use it in GitHub Desktop.
Save InAnimaTe/ee004d4a9b804cb73785519df6b0682c to your computer and use it in GitHub Desktop.
Iptables Safeclear Function
# setup for easy management of iptables
# This function makes it safer to do iptables clear and set operations.
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
FLUSH_WAIT=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 $FLUSH_WAIT 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!) | <file> (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
}
@InAnimaTe
Copy link
Author

Pulling out of my zshrc so decided to put here for public consumption; don't really do many iptables op anymore :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment