Sshuttle firewall rules cleaner for iptables
/ssh/clean-sshuttle-rules.sh
Sometimes you’re working with a SSH tunnel using the sshuttle
utility and the
tunnel is abruptly closed. You may have been disconnected from the network, or
changed from one network to another, for example connecting to a VPN; you could
have sshuttle
running in a terminal window and you closed it by accident, or
it may have been killed for whatever reason.
In those cases, sshuttle
wouldn’t have had a chance to clean the firewall
rules that it created. If you’re not aware of that, you’ll see that trying to
open a new SSH session anywhere will result in a connection refused error.
That’s because the leftover firewall rules are trying to redirect your SSH
connections to a port in your own machine that’s no longer open.
This script takes care of removing those rules. Mind you, this version only
works for Linux, since it only cleans iptables
rules.
Finally, you can pass the argument noop
to the script to only view what rules
would be removed without touching anything.
Download
this script
Secondary click/Save as…
#!/usr/bin/env bash
#
# clean-sshuttle-rules.sh
# Copyright 2020 eth0 <ethernet.zero@gmail.com>
#
# This work is free. You can redistribute it and/or modify it under the terms of
# the ISC License.
#
if [[ "$(id -u)" != 0 ]]; then
exec sudo "$0" "$@"
fi
[[ "$1" == noop ]] && noop=1
readarray -t rules < <(
iptables-save \
| grep 'j sshuttle' \
| grep -vf <(ss -plant | awk '/sshuttle/{split($4, a, ":"); print "sshuttle-" a[2]}') \
| sed 's/^-A/-D/g'
)
echo "Cleaning ${#rules[@]} iptables rules${noop+ (not really)}"
if [[ -z "$noop" ]]; then
(( ${#rules[@]} > 0 )) && echo
for r in "${rules[@]}"; do
echo "$r"
iptables -t nat $r
done
(( ${#rules[@]} > 0 )) && echo
fi
readarray -t chains < <(
iptables-save \
| grep ':sshuttle' \
| awk '{print $1}' \
| cut -d: -f2 \
| grep -vf <(ss -plant | awk '/sshuttle/{split($4, a, ":"); print "sshuttle-" a[2]}')
)
echo "Removing ${#chains[@]} iptables chains${noop+ (not really)}"
if [[ -z "$noop" ]]; then
(( ${#chains[@]} > 0 )) && echo
for i in "${chains[@]}"; do
echo "$i"
iptables -t nat -F $i
iptables -t nat -X $i
done
(( ${#chains[@]} > 0 )) && echo
fi