from colorama import Fore
from pprint import pprint
import sys
import os
import psutil
from glob import glob
sys.path.insert(0, "../..")
from utils.print import *


reverse_engineering_tools = ["ghidra", "radare2", "r2", "ida", "binwalk",
							"x32dbg", "x64dbg", "olly", "windbg", "immunity",
							"wireshark", "dumpcap"]

#####
# Process Hunting
#####


def get_process_list():
	"""
	Get process list and isolate binary name / command run.
	# TODO: Add option to sort list of processes by memory/CPU usage
	"""
	processes = set()
	# Iterate over all running process
	for proc in psutil.process_iter():
		try:
			# Get process name from process object.
			procName = proc.name()
			processes.add(procName)
		except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
			pass

	return processes


def crosscheck_reverse_engineering_tools(processes=None, binaries=None):
	"""
	processes and binaries are both lists, but only one should be passed
	to the function at a time.
	"""
	if processes:
		suspicious_procs = set()
		for process in processes:
			[suspicious_procs.add(process) for tool in reverse_engineering_tools if process.lower() in tool]

		return suspicious_procs
	elif binaries:
		suspicious_binaries = set()
		for path in binaries:
			name = path.split("/")[-1].lower()
			[suspicious_binaries.add(path) for tool in reverse_engineering_tools if name in tool]

		return suspicious_binaries


########
# Path Hunting
########

def get_all_possible_binaries_from_PATH():
	paths = os.environ["PATH"].split(":")

	for path in paths:
		if not path.endswith("/"):
			path += "/"
		path += "*"

	paths = set()
	[paths.update(glob(path)) for path in paths]
	assert paths is not None
	return paths


def main():
	"""
	Looks for reverse engineering tools in $PATH and in process list.
	"""
	print_section_header("Searching for Reverse Engineering Tools...", Fore.BLUE)

	print_blue("Looking through running processes.")
	processes = get_process_list()
	suspicious_procs = crosscheck_reverse_engineering_tools(processes)
	if len(suspicious_procs) != 0:
		print_red("Suspected analysis processes found.\n")
		pprint(list(suspicious_procs))
	else:
		print_green("No suspicious processes found.\n")

	print_blue("Looking through $PATH.")
	binaries = get_all_possible_binaries_from_PATH()
	suspicious_binaries = crosscheck_reverse_engineering_tools(binaries)
	if len(suspicious_binaries) != 0:
		print_red("Suspected analysis tools found.\n")
		pprint(list(suspicious_binaries))
	else:
		print_green("No suspicious tools found.\n")


if __name__ == '__main__':
	main()
