WireGuard: add clean reinstall flow and bootstrap wg-install
This commit is contained in:
@@ -39,25 +39,70 @@ load_meta() {
|
||||
|
||||
WG_INTERFACE="${WG_INTERFACE:-wg0}"
|
||||
WG_NETWORK="${WG_NETWORK:-10.66.66.0/24}"
|
||||
WG_ADDRESS="${WG_ADDRESS:-10.66.66.1/24}"
|
||||
WG_PORT="${WG_PORT:-51820}"
|
||||
SERVER_PUBLIC_IP="${SERVER_PUBLIC_IP:-}"
|
||||
SERVER_DNS="${SERVER_DNS:-1.1.1.1}"
|
||||
WG_CONF="/etc/wireguard/${WG_INTERFACE}.conf"
|
||||
}
|
||||
|
||||
ip_to_int() {
|
||||
local ip="$1"
|
||||
local o1 o2 o3 o4
|
||||
IFS='.' read -r o1 o2 o3 o4 <<< "$ip"
|
||||
echo $(( (o1 << 24) + (o2 << 16) + (o3 << 8) + o4 ))
|
||||
}
|
||||
|
||||
int_to_ip() {
|
||||
local n="$1"
|
||||
printf '%d.%d.%d.%d' \
|
||||
$(( (n >> 24) & 255 )) \
|
||||
$(( (n >> 16) & 255 )) \
|
||||
$(( (n >> 8) & 255 )) \
|
||||
$(( n & 255 ))
|
||||
}
|
||||
|
||||
cidr_bounds() {
|
||||
local cidr="$1"
|
||||
local ip prefix
|
||||
IFS='/' read -r ip prefix <<< "$cidr"
|
||||
[[ -n "$ip" && -n "$prefix" ]] || return 1
|
||||
|
||||
local ip_int mask net broadcast
|
||||
ip_int="$(ip_to_int "$ip")"
|
||||
if ((prefix == 0)); then
|
||||
mask=0
|
||||
else
|
||||
mask=$(( (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF ))
|
||||
fi
|
||||
net=$(( ip_int & mask ))
|
||||
broadcast=$(( net | ((~mask) & 0xFFFFFFFF) ))
|
||||
echo "${net} ${broadcast}"
|
||||
}
|
||||
|
||||
next_client_ip() {
|
||||
local network="$1"
|
||||
local base
|
||||
base="${network%.*}"
|
||||
local net_start net_end
|
||||
read -r net_start net_end < <(cidr_bounds "$network") || return 1
|
||||
((net_end - net_start >= 3)) || return 1
|
||||
|
||||
local server_ip server_ip_int
|
||||
server_ip="${WG_ADDRESS%%/*}"
|
||||
server_ip_int="$(ip_to_int "$server_ip")"
|
||||
|
||||
local first_host last_host
|
||||
first_host=$((net_start + 1))
|
||||
last_host=$((net_end - 1))
|
||||
|
||||
local used
|
||||
used="$(grep -E '^AllowedIPs\s*=\s*' "$WG_CONF" | awk -F'=' '{print $2}' | tr ',' '\n' | sed 's/ //g' | grep -E '^10\.[0-9]+\.[0-9]+\.[0-9]+/32$' | sed 's#/32##' || true)"
|
||||
used="$(grep -E '^AllowedIPs\s*=\s*' "$WG_CONF" | awk -F'=' '{print $2}' | tr ',' '\n' | sed 's/ //g' | grep -E '^([0-9]{1,3}\.){3}[0-9]{1,3}/32$' | sed 's#/32##' || true)"
|
||||
|
||||
local i candidate
|
||||
for i in $(seq 2 254); do
|
||||
candidate="${base}.${i}"
|
||||
if ! grep -qx "$candidate" <<< "$used"; then
|
||||
echo "${candidate}/32"
|
||||
local candidate_int candidate_ip
|
||||
for ((candidate_int = first_host; candidate_int <= last_host; candidate_int++)); do
|
||||
((candidate_int == server_ip_int)) && continue
|
||||
candidate_ip="$(int_to_ip "$candidate_int")"
|
||||
if ! grep -qx "$candidate_ip" <<< "$used"; then
|
||||
echo "${candidate_ip}/32"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
Reference in New Issue
Block a user