Skip to content

Instantly share code, notes, and snippets.

@cyphunk
Last active April 13, 2023 15:44
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 cyphunk/cbfba8954f5272586f6f8cfbd61cfadc to your computer and use it in GitHub Desktop.
Save cyphunk/cbfba8954f5272586f6f8cfbd61cfadc to your computer and use it in GitHub Desktop.
torforced runs command with network access restricted to torport (or specified network port)
# provide torport and then command + args
echo $1 | grep -E -q '^[0-9]+$' || echo "args: torport command (e.g. 9050 or 9150). Note, this command does not automatically forward traffic of command through tor, it only restricts network acces of command to torport. You must configure the target application to use tor/socks/whatever independently. Test with command 'printf \"GET / HTTP/1.1\r\nHost: check.torproject.org\r\n\r\n\" | torforced 9050 torsocks nc check.torproject.org 80' or 'torforced 9050 torsocks curl http://checkip.dyndns.org'"
echo $1 | grep -E -q '^[0-9]+$' || exit 1
# This may not provide the same level of assuranced that tor browser does
# It just makes certain you do not do something stupid on your own
# or something unknown happening in the background.
port=$1
shift
# will setup a group,
# restrict with iptables the permitted ports for that group
# and then run application with that group
# check for dependencies
command -v sg >/dev/null || echo "missing sg (execute command as different group)"
command -v sg >/dev/null || exit 1
GRP=no-internet ## change to your taste
usr=$(whoami)
grep -q "^$GRP:" /etc/group > /dev/null || sudo groupadd $GRP || exit 1
id $usr | grep -q "$GRP" || sudo usermod -aG $GRP $usr || exit 1
echo "Flush all rules as they *could* break functionality (iptables -F OUTPUT)"
sudo iptables -F OUTPUT || exit 1
echo "Enabling rules"
# remove next line to drop all traffic, essentially run cmd without internet
sudo iptables -A OUTPUT -m owner --gid-owner $GRP -p tcp -s localhost --dport $port -j ACCEPT || exit 1
sudo iptables -A OUTPUT -m owner --gid-owner $GRP -j DROP || exit 1
sg no-internet "nc -z google.com 80" 2> /dev/null && echo WARNING internet up - stopping && exit 1
echo Internet down. that is good - continuing
sg no-internet "$*"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment