Skip to content

Instantly share code, notes, and snippets.

@icgood
Last active January 8, 2022 15:35
Show Gist options
  • Save icgood/2a557718249b897568a69f4ddf569c2d to your computer and use it in GitHub Desktop.
Save icgood/2a557718249b897568a69f4ddf569c2d to your computer and use it in GitHub Desktop.
Configure Wireguard VPN and add new peers
#!/usr/bin/env bash
#
# Reads environment file, e.g. `wg-new.env`
# Configures WireGuard if it is not yet configured
# Adds a new peer with name and IP address
# arguments
name=$1
ip=$2
# read environment
envfile=$(dirname $0)/$(basename $0 .sh).env
[ -f $envfile ] && source $envfile
# establish defaults
interface=${INTERFACE:-wg0}
conf=${CONF:-/etc/wireguard/$interface.conf}
endpoint=${ENDPOINT:?required}
dns=${DNS:-1.1.1.1, 1.0.0.1}
if [ $UID -ne 0 ]; then
>&2 echo "ERROR: requires root privileges"
exit 2
elif [ -z "$name" -o -z "$ip" ]; then
>&2 echo "usage: $0 <name> <ip>"
>&2 echo
>&2 echo "Example:"
>&2 echo " $0 test 192.168.2.99"
>&2 echo
exit 2
fi
type wg > /dev/null || exit 1
type qrencode > /dev/null || exit 1
umask 077
mkdir -p $(dirname $conf)
reboot=0
if [ ! -f $conf ]; then
echo 'net.ipv4.ip_forward=1' | tee /etc/sysctl.d/99-wireguard.conf | sysctl --load=- > /dev/null
reboot=1
defaultif=$(ip -o -4 route show to default | awk '{print $5}')
cat <<EOF > $conf
[Interface]
PrivateKey = $(wg genkey)
Address = 192.168.2.1/24
ListenPort = 51820
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o $defaultif -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o $defaultif -j MASQUERADE
EOF
systemctl enable --now wg-quick@$interface
fi
privkey=$(wg genkey)
pubkey=$(echo $privkey | wg pubkey)
pskey=$(wg genpsk)
cat <<EOF >> $conf
[Peer] # $name
PublicKey = $pubkey
PresharedKey = $pskey
AllowedIPs = $ip/32
EOF
systemctl restart wg-quick@$interface
cat <<EOF | tee >(>&2 qrencode -t ansiutf8) | cat
[Interface]
PrivateKey = $privkey
Address = $ip/24
DNS = $dns
[Peer]
PublicKey = $(wg show $interface public-key)
PresharedKey = $pskey
AllowedIPs = 0.0.0.0/0
Endpoint = $endpoint:51820
EOF
if [ $reboot -eq 1 ]; then
>&2 echo
>&2 echo "$(tput bold)*** A reboot may be required ***$(tput sgr0)"
>&2 echo
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment