Skip to content

Instantly share code, notes, and snippets.

@sirupsen
Created September 3, 2014 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirupsen/53da08ed7833b40ef425 to your computer and use it in GitHub Desktop.
Save sirupsen/53da08ed7833b40ef425 to your computer and use it in GitHub Desktop.
Script to set up port redirection and disable it again. The tricky thing here is that even when you disable the port redirect, traffic can still flow through the redirected port for already established socket sessions, but new connections can't be established. This, in addition to removing the redirect, gdbs into the process and closes the file …
#!/bin/bash
if [[ -z $1 ]]; then
echo -e "\x1b[31mMust supply src + dest port"
exit 1
fi
echo -e "\x1b[32mForwarded port $2 --> $1\x1b[33m"
sudo iptables -t nat -I OUTPUT -p tcp -o lo --dport $2 -j REDIRECT --to-ports $1
read -e -p "Hit enter to kill port redirect.."
echo "Killing iptables forward.."
sudo iptables -t nat -D OUTPUT 1
PID=$(ps aux | grep -i [r]ails | awk '{print $2}')
FD=$(sudo lsof -p $PID | grep $2 | awk '{print $4}')
if [[ -z $FD ]]; then
echo -e "\x1b[31mNo FD found"
exit 1
fi
echo "p close($FD)" | sudo gdb -p $PID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment