Created
February 5, 2020 07:18
-
-
Save tobru/c8cea16fd91b9d5096340edbec4dbff5 to your computer and use it in GitHub Desktop.
WireGuard Client Management Shell Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
IPV4_BASE=10.42.42. | |
IPV6_BASE=fd86:ea04:1115:: | |
WG_INTERFACE=wg0 | |
SERVER_PUB_KEY="MYPUBKEY" | |
ROUTED_NET="10.42.42.0/24, fd86:ea04:1115::/64" | |
#ROUTED_NET_ALL="0.0.0.0/0, ::/0" | |
SERVER_ENDPOINT="vpn.example.com:51820" | |
usage() { echo "Usage: $0 -n <string> -c <2-255> [-q <bool>]" 1>&2; exit 1; } | |
qrcode=false | |
while getopts ":n:c:q:" o; do | |
case "${o}" in | |
n) | |
name=${OPTARG} | |
[ -f "${name}.private" ] && echo "Private key for ${name} already exists" \ | |
&& exit 1 | |
;; | |
c) | |
count=${OPTARG} | |
client_ipv4="${IPV4_BASE}${count}" | |
client_ipv6="${IPV6_BASE}${count}" | |
if grep -q ${client_ipv4} /etc/wireguard/${WG_INTERFACE}.conf; then | |
echo "IPv4 ${client_ipv4} already in use" | |
exit 1 | |
fi | |
if grep -q ${client_ipv6} /etc/wireguard/${WG_INTERFACE}.conf; then | |
echo "IPv6 ${client_ipv6} already in use" | |
exit 1 | |
fi | |
;; | |
q) | |
qrcode=true | |
;; | |
*) | |
usage | |
;; | |
esac | |
done | |
shift $((OPTIND-1)) | |
# Name and count are mandatory | |
if [ -z "${name}" ] || [ -z "${count}" ]; then | |
usage | |
fi | |
echo "Creating WireGuard config for ${name}" | |
# Generate key | |
wg genkey | tee ${name}.private | wg pubkey > ${name}.public | |
chmod 0400 ${name}.private | |
priv_key=$(cat ${name}.private) | |
pub_key=$(cat ${name}.public) | |
# Configure client | |
wg set ${WG_INTERFACE} peer ${pub_key} allowed-ips ${client_ipv4}/32,${client_ipv6}/128 | |
wg-quick save ${WG_INTERFACE} | |
read -r -d '' CLIENTCONF <<EOF | |
[Interface] | |
Address = ${client_ipv4}/24 | |
Address = ${client_ipv6}/64 | |
PrivateKey = ${priv_key} | |
[Peer] | |
PublicKey = ${SERVER_PUB_KEY} | |
AllowedIPs = ${ROUTED_NET} | |
Endpoint = ${SERVER_ENDPOINT} | |
PersistentKeepalive = 10 | |
EOF | |
echo "$CLIENTCONF" | |
echo "$CLIENTCONF" > ${name}.conf | |
echo "run 'systemctl enable [email protected]' after configuration" | |
if [ "$qrcode" == "true" ]; then | |
qrencode -t ansiutf8 < ${name}.conf | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment