xiringuito/xiringuito
2017-02-08 06:05:58 +01:00

91 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# Bash SSH VPN wrapper
#
set -e
if [[ ${#} -lt 1 ]]; then
echo "Usage: ${0} [SSH_USER@]SSH_SERVER [NETWORK1, NETWORK2, ... NETWORKx]"
exit 1
fi
declare -r SSH_SERVER=${1}; shift
if [[ ${#} -gt 0 ]]; then
declare -r NETWORKS=${@}
elif [[ -x ./discover-routes ]]; then
declare -r NETWORKS=$(./discover-routes ${SSH_SERVER})
fi
declare -r IP_BASE=192.168.245
declare -r TUNNEL_ID_PATH=~/.xiringuito/tunnel_id
declare -r TUNNEL_ID_FILE=${TUNNEL_ID_PATH}/${SSH_SERVER}
if [[ ! -f ${TUNNEL_ID_FILE} ]]; then
mkdir -p ${TUNNEL_ID_PATH}
let GENERATED_ID=${RANDOM}%50+1
echo ${GENERATED_ID} >${TUNNEL_ID_FILE}
fi
declare -r TUNNEL_ID=$(cat ${TUNNEL_ID_FILE})
declare -r REMOTE_PATH="/tmp/xiringuito.${TUNNEL_ID}"
declare -r SSH_OPTS="-oLogLevel=${SSH_LOG_LEVEL:-QUIET} -oConnectTimeout=10"
cd $(dirname ${0})
trap teardown EXIT
function teardown() {
set +e
echo "Tearing down tunnel..."
if [[ -f /etc/resolv.conf.orig ]]; then
sudo cp /etc/resolv.conf.orig /etc/resolv.conf
fi
if [[ ${SSH_PID} ]]; then
kill ${SSH_PID}
fi
./scripts/client-teardown.sh ${TUNNEL_ID}
ssh ${SSH_OPTS} ${SSH_SERVER} pkill -f ${REMOTE_PATH}/server-execute.sh
echo "DONE"
}
echo "TUNNEL ID: ${TUNNEL_ID}"
./scripts/client-setup.sh ${TUNNEL_ID} ${IP_BASE}
set +e
for NETWORK in ${NETWORKS}; do
echo "> ROUTE: ${NETWORK}"
./scripts/client-route.sh ${TUNNEL_ID} ${NETWORK}
done
set -e
ssh ${SSH_OPTS} ${SSH_SERVER} mkdir -p ${REMOTE_PATH}
scp ${SSH_OPTS} ./scripts/server-*.sh ${SSH_SERVER}:${REMOTE_PATH} >/dev/null
ssh ${SSH_OPTS} ${SSH_SERVER} ${REMOTE_PATH}/server-setup.sh ${TUNNEL_ID} ${IP_BASE}
sleep 1; echo -n "SERVER: ${SSH_SERVER} ... "
ssh ${SSH_OPTS} -w ${TUNNEL_ID}:${TUNNEL_ID} ${SSH_SERVER} ${REMOTE_PATH}/server-execute.sh ${TUNNEL_ID} ${IP_BASE} &
SSH_PID=${!}
sleep 3
if [[ ! ${NO_DNS} && ! -z "${NETWORKS}" && ! "$(grep xiringuito /etc/resolv.conf)" ]]; then
echo
echo "* Will now replace your DNS config with one fetched from the SSH server."
echo "* Set enviromental variable 'NO_DNS', if you do not want this to happen."
REMOTE_RESOLV_CONF=$(ssh ${SSH_OPTS} ${SSH_SERVER} cat /etc/resolv.conf | grep -v "[#;]" )
sudo cp /etc/resolv.conf /etc/resolv.conf.orig
if [[ "${REMOTE_RESOLV_CONF}" =~ nameserver ]]; then
echo "--- resolv.conf ---"
echo "# Added by xiringuito" | sudo tee /etc/resolv.conf
echo "${REMOTE_RESOLV_CONF}" | sudo tee -a /etc/resolv.conf
echo "nameserver 8.8.8.8" | sudo tee -a /etc/resolv.conf
echo "--- resolv.conf ---"
fi
fi
while true; do sleep 60000; done