Skip to content

Instantly share code, notes, and snippets.

@stenehall
Forked from robinlandstrom/new-wireguard-peer.sh
Last active April 2, 2024 13:50
Show Gist options
  • Save stenehall/dc33d17243f3682b90a0663c552aa7ee to your computer and use it in GitHub Desktop.
Save stenehall/dc33d17243f3682b90a0663c552aa7ee to your computer and use it in GitHub Desktop.
Script to automatically add configration for a new peer to a wireguard server. It will then print a QR code to the console that can be used to add the config to the Android or OS X wireguard client.
#!/bin/bash
readonly INTERFACE="wg0"
# Generate peer keys
readonly PRIVATE_KEY=$(wg genkey)
readonly PUBLIC_KEY=$(echo ${PRIVATE_KEY} | wg pubkey)
readonly PRESHARED_KEY=$(wg genpsk)
# Read server key from interface
readonly SERVER_PUBLIC_KEY=$(wg show ${INTERFACE} public-key)
# Get next free peer IP (This will break after x.x.x.255)
readonly PEER_ADDRESS=$(wg show ${INTERFACE} allowed-ips | cut -f 2 | awk -F'[./]' '{print $1"."$2"."$3"."1+$4"/"$5}' | sort -t '.' -k 1,1 -k 2,2 -k 3,3 -k 4,4 -n | tail -n1)
# readonly PEER_ENDPOINT=$(wg show wg0 endpoints | cut -f 2 | head -n 1)
readonly PEER_ENDPOINT=$(cat /etc/wireguard/wg0.conf | tail -n1 | cut -f 3 -d \ )
# Add peer
wg set ${INTERFACE} peer ${PUBLIC_KEY} preshared-key <(echo ${PRESHARED_KEY}) allowed-ips ${PEER_ADDRESS}
# Logging
echo "Added peer ${PEER_ADDRESS} with public key ${PUBLIC_KEY}"
# Generate peer config QR code
cat << END_OF_CONFIG | qrencode -t ANSIUTF8
[Interface]
Address = ${PEER_ADDRESS}
PrivateKey = ${PRIVATE_KEY}
DNS = 10.0.0.204
[Peer]
PublicKey = ${SERVER_PUBLIC_KEY}
PresharedKey = ${PRESHARED_KEY}
AllowedIPs = 0.0.0.0/0
Endpoint = ${PEER_ENDPOINT}
END_OF_CONFIG
cat << END_OF_CONFIG > $1.conf
[Interface]
Address = ${PEER_ADDRESS}
PrivateKey = ${PRIVATE_KEY}
DNS = 10.0.0.204
[Peer]
PublicKey = ${SERVER_PUBLIC_KEY}
PresharedKey = ${PRESHARED_KEY}
AllowedIPs = 0.0.0.0/0
Endpoint = ${PEER_ENDPOINT}
END_OF_CONFIG
cat << END_OF_CONFIG >> wg0.conf
[Peer]
PublicKey = ${PUBLIC_KEY}
AllowedIPs = ${PEER_ADDRESS}/32
Endpoint = ${PEER_ENDPOINT}
END_OF_CONFIG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment