Skip to content

Instantly share code, notes, and snippets.

@fruzyna
Created July 10, 2021 14:41
Show Gist options
  • Save fruzyna/e8ebfae37d41c918b80ee9c3d3aa4ccf to your computer and use it in GitHub Desktop.
Save fruzyna/e8ebfae37d41c918b80ee9c3d3aa4ccf to your computer and use it in GitHub Desktop.
Generate wireguard configs for a single server many client config
#!/bin/bash
# configuration
host=HOST_NAME
hostif=HOST_INTERFACE
ip=IP_RANGE # 192.168.0
addr=HOST_EXTERNAL_IP
iaddr=HOST_INTERNAL_IP
port=HOST_PORT
dns=DNS_SERVER
allowed="0.0.0.0/0"
# check for name parameter
if [ $# -lt 1 ]; then
echo "Requires at least a name parameter"
exit 1
elif [[ $1 != -* ]]; then
name=$1
shift
fi
# check flag parameters
while [ $# -gt 0 ]; do
key=$1
case $key in
-n|--name)
name=$2
shift; shift
;;
-s|--server)
addr=$2
shift; shift
;;
-p|--port)
port=$2
shift; shift
;;
-a|--allowedIPs)
allowed=$2
shift; shift
;;
-l|--lan)
clientif="PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o $2 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o $2 -j MASQUERADE"
clientip=", $3"
shift; shift; shift
;;
-w|--wgonly)
allowed="$ip.0/24"
shift
;;
-i|--internal)
addr=$iaddr
shift
;;
-d|--dns)
dns=$2
shift;shift
;;
-q|--qr)
qr="generate"
shift
;;
*)
echo "Invalid paramter $1"
exit 2
shift
;;
esac
done
# check name
if [ -z "$name" ]; then
echo "Requires a name parameter"
exit 1
fi
if [ -f "$name.conf" ]; then
echo "Client $name already exists"
exit 3
fi
# generate keys
(umask 0077; wg genkey > $name.key)
wg pubkey < $name.key > $name.pub
(umask 0077; wg genpsk > $name.psk)
# make host file if doesn't exist
if [ ! -f "$host.conf" ]; then
# generate host keys
(umask 0077; wg genkey > $host.key)
wg pubkey < $host.key > $host.pub
# create host file
cat > $host.conf << EOL
[Interface]
Address = $ip.1
ListenPort = $port
PrivateKey = $(cat $host.key)
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o $hostif -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o $hostif -j MASQUERADE
EOL
fi
# count existing configs to get next IP address
count=$(expr $(ls -1 *.conf 2>/dev/null | wc -l) + 1)
# create peer file
cat > $name.conf << EOL
[Interface]
Address = $ip.$count
PrivateKey = $(cat $name.key)
DNS = $dns
$clientif
[Peer]
PublicKey = $(cat $host.pub)
PresharedKey = $(cat $name.psk)
EndPoint = $addr:$port
AllowedIPs = $allowed
EOL
# add to host file
cat >> $host.conf << EOL
[Peer]
PublicKey = $(cat $name.pub)
PresharedKey = $(cat $name.psk)
AllowedIPs = $ip.$count/32$clientip
EOL
# show QR code
if [[ $qr = generate ]]; then
qrencode -t ansiutf8 -r $name.conf
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment