wagon/back/lib/wg_peer_list

59 lines
1.8 KiB
Plaintext
Raw Normal View History

2022-09-06 20:57:41 -06:00
#!/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'
2022-09-11 17:07:38 -06:00
if ! [ -f "${CONFIG_FILE}" ]; then
printf 'ERROR! %s Config file not found\n' "${0}" >>"${LOGFILE}"
2022-09-11 15:38:26 -06:00
exit 6
2022-09-11 17:07:38 -06:00
fi & if ! [ ${#} -eq 2 ]; then
printf 'ERROR! Bad usage: %s %s\n' "$0" "$*" >>"${LOGFILE}"
2022-09-11 15:38:26 -06:00
exit 3
2022-09-11 17:07:38 -06:00
fi & if ! [ -x /usr/bin/wg ]; then
printf 'ERROR! %s /usr/bin/wg not found\n' "${0}" >>"${LOGFILE}"
2022-09-11 15:38:26 -06:00
exit 5
fi
2022-09-06 20:57:41 -06:00
source "${CONFIG_FILE}"
2022-09-11 15:38:26 -06:00
# Get peer IP list
if ! wg_output="$(sudo /usr/bin/wg show "${TLD}" allowed-ips)"; then
2022-09-08 21:15:30 -06:00
printf 'ERROR! Wireguard failed!\n' >>"${LOGFILE}"
2022-09-11 15:38:26 -06:00
exit 5
fi
# Filter out this user's
2022-09-08 21:15:30 -06:00
user_peers="$(grep "${1%[.:]*}" <<<"${wg_output}" 2>/dev/null)"
2022-09-11 15:38:26 -06:00
if [ "${user_peers}" == "" ]; then
2022-09-08 21:15:30 -06:00
printf "ERROR! %s accessed the dashboard but isn't on the network!\n" "${1}" >>"${LOGFILE}"
2022-09-11 15:38:26 -06:00
exit 8
fi
# Loop through each peer in parallel and do an rDNS lookup for the hostnames
do_lookup(){
2022-09-11 17:13:22 -06:00
pubkey="$(<<<"${1}" cut -d ' ' -f1)"
ips="$(<<<"${1}" cut -d ' ' -f2 | tr ' ' '\n')"
ipv4="$(<<<"${ips}" grep '\.')"
ipv6="$(<<<"${ips}" grep ':')"
ipv4="${ipv4%%/*}"
ipv6="${ipv6%%/*}"
if ! domain="$("${LIB_DIR:?}/ns_lookup_rdns" "${ipv4:?}" | xargs)"
2022-09-11 15:38:26 -06:00
then exit 4
fi
2022-09-06 20:57:41 -06:00
case "${2}" in
2022-09-08 21:15:30 -06:00
'json') printf '{"domain":"%s","ipv4":"%s","ipv6":"%s","pubkey":"%s"},' \
"${domain}" "${ipv4}" "${ipv6}" "${pubkey}";;
'tsv') printf '%s\t%s\t%s\t%s\n' "${domain}" "${ipv4}" "${ipv6}" "${pubkey}";;
2022-09-06 20:57:41 -06:00
esac
2022-09-11 15:38:26 -06:00
}; while IFS= read -r line
do do_lookup "${line}" "${2}" &
[ $( jobs | wc -l ) -ge $( nproc ) ] && wait
done <<<"${user_peers}" \
| sed 's/\n//g' | sed 's/,$//' # Remove trailing comma and newline