Last active
April 10, 2018 20:43
-
-
Save timkuijsten/1731011 to your computer and use it in GitHub Desktop.
Quick 'n dirty VPN for macOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# sshsock - Quick 'n dirty VPN for macOS | |
# | |
# Usage example: | |
# Let Apple Mail, Safari and Firefox route all traffic via your ssh server at | |
# foo.example.com by using a system-wide local SOCKS proxy: | |
# | |
# $ sshsock foo.example.com | |
# Password: | |
# Press ^C to abort | |
_port=8081 | |
_netservice="Wi-Fi" | |
_cmsock=.sshsockcm | |
_progname="$(basename $0)" | |
if [ -z "$1" -o -n "$3" ]; then | |
echo "usage: $_progname host [port]" >&2 | |
exit 1 | |
fi | |
if [ -n "$2" ]; then | |
_port="$2" | |
fi | |
if [ "$_port" -lt 1024 ]; then | |
echo "illegal port $_port" >&2 | |
exit 1 | |
fi | |
cd ~ | |
# pgrep(1) exits 0 if there is a match, 1 if there is not | |
_opid="$(pgrep -of "/bin/sh $0($|[[:blank:]])")" | |
if [ "$?" -eq 0 ]; then | |
echo "$_progname: process already exists: $_opid" >&2 | |
exit 1 | |
fi | |
# keep this in sync with the ssh command that gets executed later on | |
_opid="$(pgrep -of "ssh -MNfTxa -S $_cmsock -D127\.0\.0\.1:")" | |
if [ "$?" -eq 0 ]; then | |
echo "$_progname: ssh process exists: $_opid" >&2 | |
exit 1 | |
fi | |
if [ -e "$_cmsock" ]; then | |
echo "$_progname: socket already exists: ~/$_cmsock" >&2 | |
exit 1 | |
fi | |
# exit if any command exits >0 | |
set -e | |
_remote="$1" | |
# make sure the host is reachable | |
ping -nqc 1 "$_remote" >/dev/null || ping6 -nqc 1 "$_rmeote" >/dev/null | |
# update proxy settings and ensure control master exit | |
cleanup() { | |
sudo networksetup -setsocksfirewallproxystate "$_netservice" off | |
# first try a graceful stop if that fails a hard exit | |
ssh -q -O stop -S "$_cmsock" "$_remote" | |
if [ -e "$_cmsock" ]; then | |
ssh -O exit -S "$_cmsock" "$_remote" | |
fi | |
} | |
trap cleanup INT HUP TERM EXIT | |
ssh -MNfTxa -S "$_cmsock" -D127.0.0.1:$_port "$_remote" | |
# ensure local proxy port | |
sudo networksetup -setsocksfirewallproxy "$_netservice" 127.0.0.1 $_port off | |
# turn on the proxy | |
sudo networksetup -setsocksfirewallproxystate "$_netservice" on | |
# stay open | |
echo Press ^C to abort | |
cat |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment