#!/bin/bash ### Purpose of this script # Setup a central WireGuard instance (vpn server) to # - serve as exit node # - to generate key material / configurations for clients # - help me to memorize WireGuard basics ### Files generated: # .key - private key # .pub - public key # .psk - pre-shared key (PSK) per client # .conf - configuration file for the client ### Client configuration # - Linux # - Save .conf under /etc/wireguard/wg0.conf # - Run wg-quick up wg0 # - Android / iOS # - Scan QR-Code ### References # https://wiki.archlinux.org/title/WireGuard ### Installation # Install wireguard and QR-Code generator apt-get install --yes wireguard qrencode ### Variables hostname="vpn.example.com" server_ip='192.168.130.1/24' network='192.168.130.0/24' confdir='/etc/wireguard' interface='ens3' ### Create key material cd $confdir # Function to generate private and public keys wgkeypair() { wg genkey | (umask 0077 && tee $1.key) | wg pubkey > $1.pub; } # Function to generate the pre-shared key (PSK) for clients wgpsk() { wg genpsk | (umask 0077 && cat > $1.psk) } # Generate key-pair for the central instance wgkeypair $hostname # Generate key-pairs and PSKs for the clients (peers) peers="alice bob" for peer in $peers; do wgkeypair $peer && wgpsk $peer; done ### Configuration # Setup wireguard network interface on the client ip link add dev wg0 type wireguard ip addr add $server_ip dev wg0 wg set wg0 listen-port 51871 private-key $confdir/$hostname.key # Function to generate # - configure peers on the server # - prepare config files for the peers wgsetpeer() { peer=$1 ip=$2 wg set wg0 \ peer `cat $confdir/$peer.pub` \ preshared-key $confdir/$peer.psk \ allowed-ips $ip ip link set wg0 up cat >$confdir/$peer.conf <