from Spitzer.exploiters import *
from Spitzer.exploiters.web import screenshot
from Spitzer.config import config
import json

def exploit(nmap):
    services = reverse(nmap)
    modules = config.get_data('services')
    if 'http' in json.dumps(nmap):
        screenshot.exploit(nmap)#TODO check if there are any webservers
    categories = config.get_config('categories').replace(' ', '').split(',')

    for service in services:
        for host in services[service]:
            if not service in modules:
                continue
            module = modules[service][0]
            if module != '':

                category = eval(module + '.category')

                if not any(cat in category  for cat in categories):#TODO maken enum and run everything lower
                    continue

                port = services[service][host]
                eval(module + '.exploit(\''+ host +'\', ' + json.dumps(nmap[host]['tcp'][port]) + ',' + str(port) + ')' )

def reverse(nmap):
    result = {}

    for host in nmap:
        for port in nmap[host]['tcp']:
            service = nmap[host]['tcp'][port]['name']
            if service in result:
                result[service][host] = port
            else:
                result[service] = {host:port}

    return result