42 lines
1.5 KiB
Bash
Executable File
42 lines
1.5 KiB
Bash
Executable File
#!/bin/bash
|
|
# FILE: wg_peer_list
|
|
# DESCRIPTION: Get peers in the same subnet as an ip
|
|
# USAGE: list ip json|tsv
|
|
# ERRORS:
|
|
# 3: bad usage
|
|
# 4: nslookup failed
|
|
# 5: wg failed
|
|
# 6: Config file not found
|
|
# 7: wg not found
|
|
# 8: wg found no peers
|
|
|
|
CONFIG_FILE='/etc/wgapi/config'
|
|
[ -f "${CONFIG_FILE}" ] || ( printf "ERROR! ${0} Config file not found" >&2; exit 6 )
|
|
[ ${#} -eq 2 ] || ( printf "ERROR! Bad usage: $0 $@" >&2; exit 3 )
|
|
[ -x /usr/bin/wg ] || ( printf "ERROR! ${0} /usr/bin/wg not found" >&2; exit 5 )
|
|
|
|
source "${CONFIG_FILE}"
|
|
wg_output="$(/usr/bin/wg show ${TLD} allowed-ips)"
|
|
[ ${?} -ne 0 ] && (
|
|
printf "ERROR! Wireguard failed!\n" >>${LOGFILE}
|
|
exit 5
|
|
)
|
|
user_peers="$(grep ${1%[.:]*} <<<${wg_output} 2>/dev/null)"
|
|
[ "${user_peers}" == "" ] && (
|
|
printf "ERROR! ${1} accessed the dashboard but isn't on the network!\n" >>${LOGFILE}
|
|
exit 8
|
|
)
|
|
while IFS= read -r line; do # TODO: Do these dns lookups in parallel
|
|
pubkey="$(<<<${line} cut -d ' ' -f1)"
|
|
ips="$(<<<${line} cut -d ' ' -f2)"
|
|
ipv4="$(<<<${ips} cut -d ' ' -f1)"
|
|
ipv6="$(<<<${ips} cut -d ' ' -f2)"
|
|
ipv4="${ipv4%%/*}"
|
|
ipv6="${ipv6%%/*}"
|
|
domain="$(${LIB_DIR}/ns_lookup_rdns ${ipv4} | xargs)"
|
|
[ ${?} -ne 0 ] && exit 4 # Check if nslookup failed
|
|
case "${2}" in
|
|
'json') printf "{\"domain\":\"${domain}\",\"ipv4\":\"${ipv4}\",\"ipv6\":\"${ipv6}\",\"pubkey\":\"${pubkey}\"},";;
|
|
'tsv') printf "${domain}\t${ipv4}\t${ipv6}\t${pubkey}\n";;
|
|
esac
|
|
done <<<"${user_peers}" | sed 's/\n//g' | sed 's/,$//' # Remove trailing comma and newline |