#!/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' if ! [ -f "${CONFIG_FILE}" ]; then printf 'ERROR! %s Config file not found\n' "${0}" >>"${LOGFILE}" exit 6 fi & if ! [ ${#} -eq 2 ]; then printf 'ERROR! Bad usage: %s %s\n' "$0" "$*" >>"${LOGFILE}" exit 3 fi & if ! [ -x /usr/bin/wg ]; then printf 'ERROR! %s /usr/bin/wg not found\n' "${0}" >>"${LOGFILE}" exit 5 fi source "${CONFIG_FILE}" # Get peer IP list if ! wg_output="$(sudo /usr/bin/wg show "${TLD}" allowed-ips)"; then printf 'ERROR! Wireguard failed!\n' >>"${LOGFILE}" exit 5 fi # Filter out this user's user_peers="$(grep "${1%[.:]*}" <<<"${wg_output}" 2>/dev/null)" if [ "${user_peers}" == "" ]; then printf "ERROR! %s accessed the dashboard but isn't on the network!\n" "${1}" >>"${LOGFILE}" exit 8 fi # Loop through each peer in parallel and do an rDNS lookup for the hostnames do_lookup(){ 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)" then exit 4 fi case "${2}" in '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}";; esac }; 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