Skip to content

Instantly share code, notes, and snippets.

@Belphemur
Last active October 20, 2021 22:14
Show Gist options
  • Save Belphemur/b014a11f9ae6c20203276f214e9e7d94 to your computer and use it in GitHub Desktop.
Save Belphemur/b014a11f9ae6c20203276f214e9e7d94 to your computer and use it in GitHub Desktop.
Generate a new client configuration for WireGuard
#!/usr/bin/env bash
if [ -z "$1" ]
then
echo "$0 client-name"
exit 1
fi
SERVER_IP=192.168.22.1
PORT=51820
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
LAST_IP_FILE=$DIR/lastip
LAST_IP=$(cat $LAST_IP_FILE)
if [ -z "$LAST_IP" ]
then
LAST_IP=$SERVER_IP
fi
CLIENT_DIR=$DIR/$1
CLIENT_CONF=$DIR/$1.tar.gz
nextip(){
IP=$1
IP_HEX=$(printf '%.2X%.2X%.2X%.2X\n' `echo $IP | sed -e 's/\./ /g'`)
NEXT_IP_HEX=$(printf %.8X `echo $(( 0x$IP_HEX + 1 ))`)
NEXT_IP=$(printf '%d.%d.%d.%d\n' `echo $NEXT_IP_HEX | sed -r 's/(..)/0x\1 /g'`)
echo "$NEXT_IP"
}
PUBLIC_IP=$(dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | awk -F'"' '{ print $2}')
NEW_IP=$(nextip $LAST_IP)
mkdir -p $CLIENT_DIR
umask 077 && wg genkey | tee $CLIENT_DIR/privatekey | wg pubkey > $CLIENT_DIR/publickey && umask u=rwx,go= && cat > $CLIENT_DIR/wg0.conf << _EOF
[Interface]
Address = $NEW_IP/24
#PostUp = echo nameserver DNS_SERVER | resolvconf -a tun.%i -m 0 -x
#PostDown = resolvconf -d tun.%i
PrivateKey = $(cat $CLIENT_DIR/privatekey)
[Peer]
PublicKey = $(cat $DIR/server/publickey)
AllowedIPs = 192.168.22.0/24, 192.168.42.0/24
Endpoint = $PUBLIC_IP:$PORT
PersistentKeepalive = 25
_EOF
echo $NEW_IP > $LAST_IP_FILE
tar cafv $CLIENT_CONF $CLIENT_DIR
echo "Client configuration available: $CLIENT_CONF"
#Add to configuration
sudo wg set wg0 peer $(cat $CLIENT_DIR/publickey) allowed-ips $NEW_IP/32
#Create route
sudo ip route add $NEW_IP/32 dev wg0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment