bin/.local/bin/vpn
#!/bin/bash
# shellcheck disable=SC2086
# _______._____.__________._________
# \_ (| / ._ \ \
# \ l / |/ / / /
# \_______/ /l_____X___\______\
# \_____/
# ▓▓▓▓▓▓▓▓▓▓
# ░▓ author ▓ xero <x@xero.style>
# ░▓ code ▓ https://code.x-e.ro/dotfiles
# ░▓ mirror ▓ https://git.io/.files
# ░▓▓▓▓▓▓▓▓▓▓
# ░░░░░░░░░░
# dont run as root
[[ "$(id -u)" -eq 0 ]] && { echo "just be yourself"; exit 0; }
usage() {
me="$(basename "$(test -L "{{&blob}}" && readlink "{{&blob}}" || echo "{{&blob}}")")"
cat <<x0
_______._____.__________._________
\_ (| / ._ \ \
\ l / |/ / / /
\_______/ /l_____X___\______\
\____/
usage: ${me} [-h|-a|-s|-d|-p|-c|-q] host
-a|--account : 1password account alias
-s|--secret : 1password secret item for login
-d|--dns : private ipv4 dns server
-p|--protocol : openconnect protocol (default anyconnect)
-c|--cert : pinned tls cert hash
-q|--quit : disconnect vpn and proxy
x0
exit 0
}
function get_login() {
pass=$(op item get "" --fields password)
mfa=$(op item get "" --otp)
echo "${pass},${mfa}"
}
function get_user() {
user=$(op item get "" --fields email)
[[ -z "$user" ]] && echo "failed to get user, op signin?" && exit 1
[[ $user =~ @ ]] && user=${user//@.*//}
echo "$user"
}
function connect() {
user=
login=
host=
dns=
protocol=
cert=
[[ -z "$cert" ]] || cert="--servercert $cert"
[[ -z "$dns" ]] || export INTERNAL_IP4_DNS=$dns
echo "starting vpn processes"
echo "${login}" | /usr/sbin/openconnect \
-b -u "${user}" \
--passwd-on-stdin \
--protocol=$protocol \
-S --script "vpnns --attach" \
$cert \
"$host" && \
echo "vpn connected " && \
ln -s ~/.config/kube ~/.kube
}
function disconnect() {
echo "killing vpn processes "
pkill openconnect
pkill vpnns
[[ -d "$HOME/.vpnns-default" ]] && rm -rf "$HOME/.vpnns-default"
[[ -L "$HOME/.kube" ]] && rm ~/.kube
exit 0
}
function parse_args() {
account=''
secret=''
host=''
dns=''
protocol='anyconnect'
cert=''
options=$(getopt -o ha:s:d:p:c:q -l help,account:,secret:,dns:,protocol:,cert:,quit -- "$@") || exit 1
set -- $options
while [[ $# -gt 0 ]];do
case in
-h|--help) usage;;
-a|--account) account="${2//\'/}"; shift;;
-s|--secret) secret="${2//\'/}"; shift;;
-d|--dns) dns="${2//\'/}"; shift;;
-p|--protocol) protocol="${2//\'/}"; shift;;
-c|--cert) cert="${2//\'/}"; shift;;
-q|--quit) disconnect;;
(--) host="${2//\'/}"; shift; break;;
(-*) echo "vpn error - unrecognized option " 1>&2; usage;;
(*) break;;
esac
shift
done
[[ -z "$host" ]] && usage
[[ "$host" =~ ^(q|quit|x|exit|rip|disconnect)$ ]] && disconnect
[[ -z "$account" ]] || account="--account ${account}"
eval "$(op signin ${account})"
echo "getting credentials"
user="$(get_user $secret)"
login="$(get_login $secret)"
connect "$user" "$login" "$host" "$dns" "$protocol" "$cert"
}
# fail fast w/ proper exit codes
set -eo pipefail
# run main logic
parse_args "$@"