wggen (1188B) [raw]
1 #!/bin/sh 2 set -e 3 4 die() { 5 echo "$*" 1>&2 6 exit 1 7 } 8 9 [ -z "$1" ] && die "usage: $0 HOST" 10 11 NAME="$1" 12 DATADIR=${DATADIR:-/etc/wg} 13 HOSTFILE=${HOSTFILE:-${DATADIR}/hosts} 14 15 # Detect if name in use 16 if grep -q "^$NAME[[:space:]]" "$HOSTFILE"; then 17 die "hostname $NAME taken" 18 fi 19 20 # Get public and private keys 21 CONF="$DATADIR/$NAME" 22 mkdir -p "$CONF" 23 openssl rand -base64 32 > "$CONF/private.key" 24 25 ifconfig wg9 destroy 2>/dev/null || true 26 ifconfig wg9 create wgport 13421 wgkey "$(cat "$CONF/private.key")" 27 ifconfig wg9 | grep wgpubkey | cut -d ' ' -f 2 > "$CONF/public.key" 28 ifconfig wg9 destroy 2>/dev/null || true 29 30 # Assign an IP 31 CUR=$(tail -n 1 "$HOSTFILE" | cut -d. -f 4) 32 NEXT=$((CUR + 1)) 33 echo "$NAME 10.6.6.$NEXT" >> "$HOSTFILE" 34 35 # Generate the config 36 cat <<EOM > "$CONF/client.conf" 37 # public key: $(cat "$CONF/public.key") 38 [Interface] 39 PrivateKey = $(cat "$CONF/private.key") 40 Address = 10.6.6.$NEXT/24 41 42 [Peer] 43 PublicKey = JpsSfrcrhCcTR5bybV9YQaAV60A12heinyAiSbMK3ng= 44 AllowedIPs = 10.6.6.1/32 45 Endpoint = 45.79.221.98:7149 46 EOM 47 48 # Lastly, append to /etc/hostname.wg0 and restart it 49 cat <<EOM >> /etc/hostname.wg0 50 wgpeer $(cat "$CONF/public.key") wgaip 10.6.6.$NEXT/32 51 EOM 52 53 sh /etc/netstart