#!/bin/bash # Configures a temporary VPN tunnel (using single-use keys) to a remote host # using WireGuard: https://www.wireguard.com/ # # Author: Matt Low # HOST=$1 HOST_ADDR=$(echo ${HOST} | awk -F '@' '{ print $NF }') SERVER_ADDR=10.99.255.1/24 CLIENT_ADDR=10.99.255.2/32 DNS=8.8.8.8 echo "Generating keys..." SERVER_KEY=$(wg genkey) CLIENT_KEY=$(wg genkey) SERVER_PUB=$(wg pubkey <<< ${SERVER_KEY}) CLIENT_PUB=$(wg pubkey <<< ${CLIENT_KEY}) PSK=$(wg genpsk) echo " Server pubkey: ${SERVER_PUB}" echo " Client pubkey: ${CLIENT_PUB}" SERVER_SETUP=$(cat << END if [ -z "\$(which wg-quick 2>/dev/null)" ]; then echo "wg-quick not found, installing..." sudo apt install -y wireguard-tools 2>/dev/null \ || sudo pacman -S --noconfirm wireguard-tools 2>/dev/null \ || sudo dnf install -y wireguard-tools iptables 2>/dev/null \ [ "\$?" -eq 0 ] || { echo "Could not install wireguard-tools, aborting."; exit 1; } fi sysctl -w net.ipv4.ip_forward=1 umask 0177 cat << CONF > /tmp/tun.conf [Interface] Address = ${SERVER_ADDR} ListenPort = 51820 PrivateKey = ${SERVER_KEY} PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE [Peer] # foo PublicKey = ${CLIENT_PUB} PresharedKey = ${PSK} AllowedIPs = ${CLIENT_ADDR} CONF sudo wg-quick up /tmp/tun.conf END ) echo echo "Starting server..." ssh -T ${HOST} sh <<< "${SERVER_SETUP}" 1>/dev/null if [ "$?" -ne 0 ]; then echo "Error starting server, aborting." exit 1 fi umask 0177 cat << CONF > /tmp/tun.conf [Interface] Address = ${CLIENT_ADDR} PrivateKey = ${CLIENT_KEY} DNS = ${DNS} [Peer] PublicKey = ${SERVER_PUB} PresharedKey = ${PSK} Endpoint = ${HOST_ADDR}:51820 AllowedIPs = 0.0.0.0/0, ::/0 CONF echo echo "Starting client..." sudo wg-quick up /tmp/tun.conf # clear these variables from memory PSK= CLIENT_KEY= SERVER_KEY= sleep 1 echo sudo wg show tun echo echo "Connected! Interrupt or press Enter to disconnect and stop server." cleanup() { set -e echo echo "Stopping client..." sudo wg-quick down /tmp/tun.conf rm /tmp/tun.conf echo echo "Stopping server..." ssh -T ${HOST} <<- END wg-quick down /tmp/tun.conf rm /tmp/tun.conf END echo echo "Bye!" exit } trap cleanup INT TERM read var cleanup