#!/usr/bin/env bash # thanks to StavrosK (https://www.stavros.io/posts/how-to-configure-wireguard/) for the wonderful # documentation I originally used to get this set up ## script to set up a basic wireguard server ## Pre-requisites: ## # install wireguard according to the instructions available at # https://www.wireguard.com/install/ # the default settings use the following subnet: # ipv4: 10.25.0.0/24 # exit if a command fails set -o errexit # exit if required variables are not set set -o nounset # return the exit status of the final command before a failure set -o pipefail # this script should be run as root if [[ ${EUID} -ne 0 ]]; then echo "This script must be run as root" exit 1 fi # error out if the wireguard kernel module does not exist if lsmod | grep wireguard >/dev/null 2>&1; then : else echo -e "\\nPlease install the Wireguard kernel module by following the instructions" echo -e "available at https://www.wireguard.com/install/ before running this script\\n" exit 1 fi # set wan interface name WAN_INTERFACE="eth0" # set wireguard tunnel interface name WG_INTERFACE="wg0" # set wireguard port PORT="51820" # set the private ipv4 subnet to be used SUBNET_V4="10.25.0" MASK_V4="24" # generate keys for wireguard server umask 077 wg genkey | tee /etc/wireguard/privatekey | wg pubkey | tee /etc/wireguard/publickey # store the private key for use in the config file PRIVATE_KEY="$(cat /etc/wireguard/privatekey)" # generate wireguard config file cat </etc/wireguard/"${WG_INTERFACE}".conf [Interface] PrivateKey = ${PRIVATE_KEY} Address = ${SUBNET_V4}.1/${MASK_V4} ListenPort = ${PORT} PostUp = iptables -A FORWARD -i ${WG_INTERFACE} -j ACCEPT; iptables -t nat -A POSTROUTING -o ${WAN_INTERFACE} -j MASQUERADE PostDown = iptables -D FORWARD -i ${WG_INTERFACE} -j ACCEPT; iptables -t nat -D POSTROUTING -o ${WAN_INTERFACE} -j MASQUERADE EOL # enable ipv4 forwarding for this session sysctl -w net.ipv4.ip_forward=1 # enable ipv4 forwarding on boot echo "net.ipv4.ip_forward=1" | tee -a /etc/sysctl.conf # start wireguard wg-quick up "${WG_INTERFACE}" # restart wireguard on boot systemctl enable wg-quick@"${WG_INTERFACE}"