import os
import json
import unittest
from exploits.exploit import LinuxExploit
from exploits.linux.CVE20173630 import CVE20173630
from exploits.mac.CVE20155889 import CVE20155889
from exploits.mac.CVE20164656 import CVE20164656
from constants import *


class TestExploitSetup(unittest.TestCase):
	def test_write_exploit_source(self):
		test_exploit = LinuxExploit()
		test_exploit.write_exploit_source()
		print("randomstring {}".format(test_exploit.source_c_path))
		self.assertTrue(os.path.exists(test_exploit.source_c_path))
		# remove it so it's not in the project
		if os.path.exists(test_exploit.source_c_path):
			os.remove(test_exploit.source_c_path)

	def test_compile_exploit_source(self):
		test_exploit = LinuxExploit()
		test_exploit.write_exploit_source()
		test_exploit.exploit_compile()
		self.assertTrue(os.path.exists(test_exploit.compilation_path))
		# remove files so they're not in the project
		if os.path.exists(test_exploit.source_c_path):
			os.remove(test_exploit.source_c_path)
		if os.path.exists(test_exploit.compilation_path):
			os.remove(test_exploit.compilation_path)

	def test_exploits_in_project(self):
		test_exploits = [
			CVE20173630(),
			CVE20155889()
		]
		for exploit in test_exploits:
			exploit.write_exploit_source()
			exploit.exploit_compile()
			self.assertTrue(os.path.exists(exploit.source_c_path))
			self.assertTrue(os.path.exists(exploit.compilation_path))
			if os.path.exists(exploit.source_c_path):
				os.remove(exploit.source_c_path)
			if os.path.exists(exploit.compilation_path):
				os.remove(exploit.compilation_path)

	def test_tricky_mac_exploit(self):
		test_exploit = CVE20164656()
		test_exploit.write_exploit_source()
		test_exploit.exploit_compile()
		for exploit_source in test_exploit.exploit_sources.keys():
			source_path = os.path.join(PLAYGROUND_PATH, exploit_source)
			self.assertTrue(os.path.exists(source_path))
		self.assertTrue(os.path.exists(test_exploit.compilation_path))

		# cleanup
		for exploit_source in test_exploit.exploit_sources.keys():
			source_path = os.path.join(PLAYGROUND_PATH, exploit_source)
			if os.path.exists(test_exploit.source_c_path):
				os.remove(source_path)
		if os.path.exists(test_exploit.compilation_path):
			os.remove(test_exploit.compilation_path)


if __name__ == "__main__":
	unittest.main()
