70 lines
1.3 KiB
Bash
70 lines
1.3 KiB
Bash
#!/bin/bash
|
|
# Generate a WireGuard peer config and update wg0.conf automatically.
|
|
|
|
set -e
|
|
|
|
if [ -z "$1" ]; then
|
|
echo "Usage: $0 <peername>"
|
|
exit 1
|
|
fi
|
|
|
|
PEER=$1
|
|
WG_DIR="/etc/wireguard"
|
|
VPN_NET="10.20.0"
|
|
CONF="$WG_DIR/wg0.conf"
|
|
|
|
# Find next free IP
|
|
USED_IPS=$(grep AllowedIPs "$CONF" | awk -F'[ ./]' '{print $7}')
|
|
FREE_IP=$(comm -23 \
|
|
<(seq 2 254 | sort) \
|
|
<(printf "%s\n" $USED_IPS | sort) \
|
|
| head -n 1)
|
|
|
|
if [ -z "$FREE_IP" ]; then
|
|
echo "No free VPN IPs left" >&2
|
|
exit 1
|
|
fi
|
|
|
|
CLIENT_IP="10.20.0.$FREE_IP"
|
|
|
|
# Generate client keypair
|
|
wg genkey | tee "$PEER.key" | wg pubkey > "$PEER.pub"
|
|
CLIENT_PRIVATE_KEY=$(cat "$PEER.key")
|
|
CLIENT_PUBLIC_KEY=$(cat "$PEER.pub")
|
|
|
|
# Server public key
|
|
SERVER_PUBLIC_KEY=$(wg show wg0 public-key)
|
|
|
|
# Generate client config
|
|
cat > "$PEER.conf" <<EOF
|
|
[Interface]
|
|
PrivateKey = $CLIENT_PRIVATE_KEY
|
|
Address = $CLIENT_IP/32
|
|
DNS = 1.1.1.1
|
|
|
|
[Peer]
|
|
PublicKey = $SERVER_PUBLIC_KEY
|
|
Endpoint = <SERVER_PUBLIC_IP>:51820
|
|
AllowedIPs = 10.20.0.0/24
|
|
PersistentKeepalive = 25
|
|
EOF
|
|
|
|
echo "Client config written to $PEER.conf"
|
|
|
|
# Add to server config
|
|
cat >> "$CONF" <<EOF
|
|
|
|
# Peer: $PEER
|
|
[Peer]
|
|
PublicKey = $CLIENT_PUBLIC_KEY
|
|
AllowedIPs = $CLIENT_IP/32
|
|
EOF
|
|
|
|
echo "Added peer $PEER to $CONF"
|
|
|
|
# Apply live without restart
|
|
wg set wg0 peer "$CLIENT_PUBLIC_KEY" allowed-ips "$CLIENT_IP/32"
|
|
|
|
echo "Peer added live to WireGuard"
|
|
|