Skip to content

Instantly share code, notes, and snippets.

@cyphunk
Last active October 21, 2016 14:00
Show Gist options
  • Save cyphunk/20b309aa24bbbbec5decdb1bcafbab0a to your computer and use it in GitHub Desktop.
Save cyphunk/20b309aa24bbbbec5decdb1bcafbab0a to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# As this script may be called from sudo, suggest safe use:
l=($(ls -l $0))
[ ${l[0]:2:1} != "-" ] && [ "${l[2]}" != "root" ] ||
[ ${l[0]:5:1} != "-" ] && [ "${l[3]}" != "root" ] ||
[ ${l[0]:8:1} != "-" ] || [ -L $0 ] || [ -L ${0%/*} ] &&
{ echo -e "no symlinks and only root should be able to modify.\n${l[@]}"; exit 1;}
echo "! Do not use this for anonymity, only proxies tcp+udp"
if [ ! $2 ]; then echo "usage: $0 [proxy_ip:]<port> <command> [arguments]"; exit 1; fi
PROXY="$1"
shift
shopt -s extglob
if [ "${PROXY/+([0-9])/isport}" == "isport" ]; then
PROXY="127.0.0.1:$PROXY"
elif [ "${PROXY/+([0-9]).+([0-9]).+([0-9]).+([0-9]):*/isip+port}" != "isip+port" ]; then
echo "argument 1 must have format IP:PORT"
exit
fi
GRP=proxy-all # change to your taste
# CREATE GROUP AND ADD USER
usr=$(whoami)
grep -q "^$GRP:" /etc/group > /dev/null || sudo groupadd $GRP || exit
id $usr | grep -q "$GRP" || sudo usermod -aG $GRP $usr || exit
if ! sudo iptables -L | grep -q $GRP; then
echo "ADDING RULES"
set -x
sudo iptables -t mangle -A OUTPUT -m owner --gid-owner $GRP -j MARK --set-mark 2
sudo iptables -t mangle -A OUTPUT -m owner --gid-owner $GRP -j CONNMARK --save-mark
sudo iptables -t nat -A OUTPUT -m mark --mark 2 -p tcp --dport 0:65535 -j DNAT --to-destination $PROXY
# cannot do both udp and tcp at same time
#sudo iptables -t nat -A OUTPUT -m mark --mark 2 -p udp --dport 0:65535 -j DNAT --to-destination $PROXY
sudo iptables -A OUTPUT -m mark --mark 2 -j LOG --log-prefix 'PROXY: ' --log-level 0
fi
sg $GRP "$*"
if [ $? -eq 1 ]; then
echo "PROXY DOWN? <<<<<<<<<<<<<<<<<"
fi
echo "REMOVING RULES"
sudo iptables -t mangle -D OUTPUT -m owner --gid-owner $GRP -j MARK --set-mark 2
sudo iptables -t mangle -D OUTPUT -m owner --gid-owner $GRP -j CONNMARK --save-mark
sudo iptables -t nat -D OUTPUT -m mark --mark 2 -p tcp --dport 0:65535 -j DNAT --to-destination $PROXY
#sudo iptables -t nat -D OUTPUT -m mark --mark 2 -p udp --dport 0:65535 -j DNAT --to-destination $PROXY
sudo iptables -D OUTPUT -m mark --mark 2 -j LOG --log-prefix 'PROXY: ' --log-level 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment