# shellcheck shell=sh
# vpn.sh — private OpenVPN profile management for HTB lab packs.
vpn__safe_name() {
_name=${1%.ovpn}
case $_name in
''|*[!A-Za-z0-9._-]*) pe_die "invalid profile name: $1" ;;
esac
printf '%s' "$_name"
}
vpn_import() {
[ -f "${1:-}" ] || pe_die "usage: pe vpn import <file.ovpn> [name]"
pe_dirs_ensure
_name=$(vpn__safe_name "${2:-$(basename "$1" .ovpn)}")
_dest="$PE_VPN_DIR/$_name.ovpn"
if [ -e "$_dest" ]; then
pe_confirm "replace existing profile $_name?" || { pe_warn 'aborted'; return 1; }
fi
install -m 600 -- "$1" "$_dest" || pe_die "could not import $1"
pe_ok "HTB VPN profile imported: $_dest"
}
vpn_ls() {
pe_dirs_ensure
_seen=0
for _profile in "$PE_VPN_DIR"/*.ovpn; do
[ -f "$_profile" ] || continue
_seen=1
printf '%s\n' "$(basename "$_profile" .ovpn)"
done
[ "$_seen" = 1 ] || pe_empty "no profiles — pe vpn import ~/Downloads/<pack>.ovpn"
}
vpn__pick() {
pe_dirs_ensure
if [ -n "${1:-}" ]; then
_name=$(vpn__safe_name "$1")
_profile="$PE_VPN_DIR/$_name.ovpn"
[ -f "$_profile" ] || pe_die "no VPN profile named $_name"
printf '%s' "$_profile"
return 0
fi
set -- "$PE_VPN_DIR"/*.ovpn
[ -f "$1" ] || pe_die "no VPN profiles — run: pe vpn import ~/Downloads/<pack>.ovpn"
if [ "$#" -eq 1 ]; then
printf '%s' "$1"
elif command -v fzf >/dev/null 2>&1 && [ -t 0 ]; then
printf '%s\n' "$@" | fzf --prompt='HTB VPN> '
else
pe_die "multiple VPN profiles; choose one: pe vpn up <name>"
fi
}
vpn_up() {
pe_need openvpn sudo
_profile=$(vpn__pick "${1:-}") || return 1
chmod 600 "$_profile" 2>/dev/null || true
pe_info "connecting with $(basename "$_profile")"
pe_warn "keep this window open; press Ctrl-C to disconnect"
pe_warn "do not use a local VPN and HTB Pwnbox at the same time"
exec sudo openvpn --config "$_profile"
}
vpn_status() {
if command -v ip >/dev/null 2>&1; then
_rows=$(ip -o -4 addr show 2>/dev/null \
| awk '$2 ~ /^(tun|tap|wg)/ {print $2 " | " $4}')
elif command -v ifconfig >/dev/null 2>&1; then
_rows=$(ifconfig 2>/dev/null | awk '
/^[[:alnum:]][^:]*:/ {iface=$1; sub(/:$/, "", iface)}
iface ~ /^(utun|tun|tap|wg)/ && $1 == "inet" {print iface " | " $2}')
else
_rows=""
fi
if [ -n "$_rows" ]; then
printf '%s\n' "$_rows" | pe_table 'INTERFACE|ADDRESS'
else
pe_empty 'no tun/tap/utun/wg lab interface is active'
return 1
fi
}
vpn_route() {
[ -n "${1:-}" ] || pe_die "usage: pe vpn route <target-ip>"
if command -v ip >/dev/null 2>&1; then
ip route get "$1" || return 1
elif command -v route >/dev/null 2>&1; then
route -n get "$1" || return 1
else
pe_die "neither ip nor route is available"
fi
}
vpn_main() {
_verb=${1:-status}; [ $# -gt 0 ] && shift
case $_verb in
import|add) vpn_import "$@" ;;
ls|list) vpn_ls ;;
up|connect) vpn_up "$@" ;;
status) vpn_status ;;
route|test) vpn_route "$@" ;;
-h|--help|help)
printf 'pe vpn <import FILE [NAME]|ls|up [NAME]|status|route IP>\n'
;;
*) pe_die "unknown: pe vpn $_verb (try 'pe vpn help')" ;;
esac
}