#!/bin/bash

## Copyright (C) 2012 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

set -x
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose
set -o pipefail

if [ "$(id -u)" != "0" ]; then
   true "ERROR: This script must be run as root (sudo)"
   exit 1
fi

error_handler() {
   true "##############################"
   true "## ERROR detected!"
   true "## BASH_COMMAND: ${BASH_COMMAND}"
   true "## Please report this bug!"
   true "##############################"

   exit 1
}

trap "error_handler" ERR

config_file="/etc/torrc.d/65_leak_tests.conf"

exit_function() {
   true "INFO: Listening for leaks stopped."

   true "INFO: Reverting '${config_file}' to original state."

   search="\
ReachableDirAddresses *:80
ReachableORAddresses *:443
FascistFirewall 1"

   replace="
#ReachableDirAddresses *:80
#ReachableORAddresses *:443
#FascistFirewall 1"

   str_replace "${search}" "${replace}" "${config_file}"

   true "INFO: Reloading Tor, using normal settings again"
   systemctl --no-pager reload tor@default
}

trap "exit_function" EXIT

true "INFO: Setting capabilities to run wireshark with user privileges."
setcap cap_net_raw,cap_net_admin=eip /usr/bin/dumpcap

true "INFO: Modifying '${config_file}' for leak testing."

search="\
#ReachableDirAddresses *:80
#ReachableORAddresses *:443
#FascistFirewall 1"

replace="
ReachableDirAddresses *:80
ReachableORAddresses *:443
FascistFirewall 1"

str_replace "${search}" "${replace}" "${config_file}"

true "INFO: Restarting Tor, only using port 80 and 443..."
systemctl --no-pager reload tor@default
systemctl --no-pager status tor@default

true "NOTE: You must be logged in as user and start this script with sudo leaktest"
true "NOTE: Otherwise you will see a lot tshark error messages."
true "INFO: Starting tshark as user... To stop press CTRL + C."

## HARDCODED!
sudo --non-interactive -u user tshark -i eth0 -f "ip and src host 10.0.2.15 and not (port 80 or port 443 or port 9001 or port 9030 or ssh)"
